# [Tutor] numbers and ranges

Jon Crump jjcrump at myuw.net
Mon May 28 00:09:20 CEST 2007

```Kent,

That's damned clever! Your solution hovers right at the limit of my
understanding, but the print statements illustrate very clearly the
operation of the function.

Many thanks!
Jon

On Sun, 27 May 2007, Kent Johnson wrote:
>> Here's a puzzle that should be simple, but I'm so used to words that
>> numbers tend to baffle me.
>>
>> I've got fields that look something like this:
>> 1942. Oct. 1,3,5,7,8,9,10
>>
>> I need to parse them to obtain something like this:
>> <sometag start="1942-10-01"/>
>> <sometag start="1942-10-03"/>
>> <sometag start="1942-10-05"/>
>> <sometag start="1942-10-07" end "1942-10-10"/>
>
> Here is a solution that uses a generator to create the ranges:
>
> def ranges(data):
>    i = iter(data)
>    first = last = i.next()
>    try:
>        while 1:
>            next = i.next()
>            if next > last+1:
>                yield (first, last)
>                first = last = next
>            else:
>                last = next
>    except StopIteration:
>        yield (first, last)
>
> print list(ranges((1,)))
> print list(ranges((1,2,3)))
> print list(ranges((1,3,5)))
> print list(ranges((1,3,5,7,8,9,10)))
>
> for start, end in ranges((1,3,5,7,8,9,10)):
>    if start == end:
>        print '<sometag start="1942-10-%02d"/>' % start
>    else:
>        print '<sometag start="1942-10-%02d" end "1942-10-%02d"/>' % (start,
> end)
```