Jon Crump wrote: > Dear all, > > 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"/> > > The xml representation is incidental, the basic problem is how to test a > list of integers to see if they contain a range, and if they do, do > something different with them.
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) Kent _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor