[Tutor] numbers and ranges
Kent Johnson
kent37 at tds.net
Tue Jun 5 12:28:16 CEST 2007
Kent Johnson wrote:
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)))
I suspected when I wrote this that if I were clever enough I could use
itertools.groupby() to solve this. It turns out that the last example at
http://docs.python.org/lib/itertools-example.html
is exactly the problem of finding runs in a sequence.
Kent
More information about the Tutor
mailing list