Range expansion: Difference between revisions

From Rosetta Code
Content added Content deleted
(Replace sample range text and add Python solution.)
m (→‎{{header|Python}}: Formatting)
Line 13: Line 13:
return lst
return lst


print(rangeexpand('-6,-3-1,3-5,7-11,14,15,17-20'))</python>
print(rangeexpand('-6,-3-1,3-5,7-11,14,15,17-20'))</lang>


'''Sample output'''
'''Sample output'''

Revision as of 05:28, 16 July 2010

Task
Range expansion
You are encouraged to solve this task according to the task description, using any language you may know.

Expand the range of integers -6,-3-1,3-5,7-11,14,15,17-20 which is in the format described in Range extraction to a list of integers.

Python

<lang python>def rangeexpand(txt):

   lst = []
   for r in txt.split(','):
       if '-' in r[1:]:
           r0, r1 = r[1:].split('-', 1)
           lst += range(int(r[0] + r0), int(r1) + 1)
       else:
           lst.append(int(r))
   return lst

print(rangeexpand('-6,-3-1,3-5,7-11,14,15,17-20'))</lang>

Sample output

[-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20]