tasks a-s
This commit is contained in:
parent
47bf37c096
commit
b83f433714
12433 changed files with 156208 additions and 123 deletions
19
Task/Range-extraction/Python/range-extraction-1.py
Normal file
19
Task/Range-extraction/Python/range-extraction-1.py
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
def rangeextract(lst):
|
||||
lenlst = len(lst)
|
||||
i, ranges = 0, []
|
||||
while i< lenlst:
|
||||
low = lst[i]
|
||||
while i <lenlst-1 and lst[i]+1 == lst[i+1]: i +=1
|
||||
hi = lst[i]
|
||||
ranges.append(
|
||||
'%i-%i' % (low, hi) if hi - low >= 2 else
|
||||
('%i,%i' % (low, hi) if hi - low == 1 else
|
||||
'%i' % low) )
|
||||
i += 1
|
||||
return ','.join(ranges)
|
||||
|
||||
lst = [ 0, 1, 2, 4, 6, 7, 8, 11, 12, 14,
|
||||
15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
|
||||
25, 27, 28, 29, 30, 31, 32, 33, 35, 36,
|
||||
37, 38, 39]
|
||||
print(rangeextract(lst))
|
||||
26
Task/Range-extraction/Python/range-extraction-2.py
Normal file
26
Task/Range-extraction/Python/range-extraction-2.py
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
def grouper(lst):
|
||||
src = iter(lst)
|
||||
acc = [ next(src) ]
|
||||
for i in src:
|
||||
if i == acc[-1] + 1: acc.append(i)
|
||||
else:
|
||||
yield acc
|
||||
acc = [i]
|
||||
yield acc
|
||||
raise StopIteration()
|
||||
|
||||
def rangegrouper(lst):
|
||||
for g in grouper(lst):
|
||||
if len(g) == 2:
|
||||
# satisfy rule that only runs longer than 2 are grouped
|
||||
a,b = g
|
||||
yield [a]
|
||||
yield [b]
|
||||
else: yield g
|
||||
raise StopIteration()
|
||||
|
||||
input= [0, 1, 2, 4, 6, 7, 8, 11, 12, 14,15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 29, 30, 31, 32, 33, 35, 36,37, 38, 39]
|
||||
print list(rangegrouper(input)) # print groups
|
||||
as_strings= ['%s%s%s' % ((g[0],'-',g[-1]) if len(g) > 1 else (g[0],'','')) for g in rangegrouper(input)]
|
||||
print as_strings
|
||||
print ', '.join(as_strings)
|
||||
Loading…
Add table
Add a link
Reference in a new issue