Parsing numeric ranges

Seldon seldon at katamail.it
Fri Feb 25 14:03:59 CET 2011


On 02/25/2011 10:44 AM, Alain Ketterlin wrote:
> Seldon<seldon at katamail.it>  writes:
>
>> I have to convert integer ranges expressed in a popular "compact"
>> notation (e.g. 2, 5-7, 20-22, 41) to a the actual set of numbers (i.e.
>> 2,5,7,20,21,22,41).
>
> What form does the input have? Are they strings, or some other
> representation?

Strings

>
> What kind of result do you need? An explicit list? A generator?

A list.


>
> Here is a naive solution where the input is a list of strings and the
> result a generator:
>
> def values(l):
>      for item in l:
>          bounds = item.split('-')
>          if len(bounds) == 1:
>              yield int(bounds[0])
>          elif len(bounds) == 2:
>              for v in range(int(bounds[0]),1+int(bounds[1])):
>                  yield v
>          else:
>              pass # ignore, or throw, or...
>
> # Use as in:
> for x in values(["1","2-3","4-10"]):
>      print x
>

Ok, tnx.



More information about the Python-list mailing list