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

Manuel Garcia news at manuelmgarcia.com
Fri May 30 22:57:01 EDT 2003


On Fri, 30 May 2003 22:51:06 GMT, Alex <delete.this.part.alex.news at attbi.com> wrote:

>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

Kick ass!

I recommend to everyone in the thread to play with this one, to fully
appreciate its majesty.

['6','7','12','mx8','mx09','mx10','mx11-12','8','9','10','foo']
-> ['6-7', '12', 'mx8-12', '8-10', 'foo']

Fantastic!

Two bugs, easily fixed:

It doesn't work for ['foo','foo1'].

Little mix-up with 'low' and 'high' in the 'if' condition,
so ['mx3-7','mx8'] doesn't work.

I am not sure if 'int(max(low2.rjust(len(high2)), high2))' always
works.  I would replace it with
'int([high2, low2][len(high2)==0])'.

I think this fixes it:

########################
## gyoung2.py

import re
names = ['6','7','12','mx3-7','mx8','mx09','mx10','mx11-12','8','9','10','foo','foo1','foo2']
for ii in xrange(len(names)-1, 0,-1):
    (base1, low1, high1),(base2, low2, high2)=(re.match(r'(\D*)(\d*)-?(\d*)', names[ii-1]).groups(), re.match(r'(\D*)(\d*)-?(\d*)', names[ii]).groups())
    if base1 == base2 and low1 and low2 and int([high1, low1][len(high1)==0])+1 == int(low2):
        names[ii-1] = '%s%d-%d' % (base1, int(low1), int([high2, low2][len(high2)==0]))
        names.pop(ii)
print names


########################

My brain is not working to make it any shorter.

Pythonic, it is not!

Manuel




More information about the Python-list mailing list