[Tutor] numbers and ranges

Bob Gailer bgailer at alum.rpi.edu
Sun May 27 22:18:38 CEST 2007


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.
>   
numList = (1, 3, 5, 7, 8, 9, 10)
inSequence = False
result = ""
priorNumber = numList[0]
for number in numList[1:]:
  if number - priorNumber == 1:
    if not inSequence:
      seqStart = priorNumber
      inSequence = True
  else:
    if inSequence:
      result += '<sometag start="1942-10-%02i" end "1942-10-%02i"/>\n' % 
(seqStart, priorNumber)
      inSequence = False
    else:
      result += '<sometag start="1942-10-%02i"/>\n' % priorNumber
  priorNumber = number
if inSequence:
  result += '<sometag start="1942-10-%02i" end "1942-10-%02i"/>\n' % 
(seqStart, priorNumber)
print result
> I'm sure this is the question of a rank tyro, but the denizens of this 
> list seem tolerant and gentle. Many thanks.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>   


-- 
Bob Gailer
510-978-4454



More information about the Tutor mailing list