[2,3,4,7] --> "2-4,7" ?

Alex delete.this.part.alex.news at attbi.com
Fri May 30 18:51:06 EDT 2003


Manuel Garcia wrote:

<snip>
> In the other solutions given, I was worried about what always happened
> to me the other dozen times I coded something like this: if there is a
> small change to the specification, my old algorithm cannot be simply
> adapted.
<snip>
> or if in
> the original list, you already had some items in the form
>        'mx8-12, mx13, mx14-17'
> and you wanted the result to be 'mx8-17'
<snip>

I agree with the sentiment completely.  Having said that, here is how I 
amused myself for the last hour:


import re
names=['6','7','mx8','mx09','mx10','8','9','10','foo']
r=re.compile(r'(\D*)(\d*)-?(\d*)')

for ii in xrange(len(names)-1, 0,-1):
  (base1, low1, high1),(base2, low2, high2)=r.match(names[ii-1]).groups(), r.match(names[ii]).groups()
  if base1==base2 and int(low1)+1==int(low2):
    names[ii-1]='%s%d-%d' %(base1, int(low1), int(max(low2.rjust(len(high2)), high2)))
    names.pop(ii)

print names


Alex






More information about the Python-list mailing list