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 _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor