iterating in reverse
Bengt Richter
bokr at oz.net
Sun Jan 19 04:55:34 EST 2003
On Sat, 18 Jan 2003 20:25:46 GMT, "Neil Hodgson" <nhodgson at bigpond.net.au> wrote:
>Steve Holden:
>
>> Here's my own non-reversing solution. Again, it would need tweaking for
>> negative numbers to avoid results like "-,123".
>>
>> def commafy(val):
>> ...
>
> Well we may as well try a one liner (almost):
>
>def commafy(val):
> u = str(val)
> return ''.join([u[i]+(['',',',''][(len(u)-i)%3]) for i in
>range(len(u))])[:-1]
>
>for i in [1, 12, 123, 1234, 12345, 123456, 1234567, 12345678]:
> print i, ":", commafy(i)
>
> Mmm, Perl envy ...
>
>>> def commafy(val):
... return reduce(lambda x,c:[x[0]+c+','[:x[1]%3==1],x[1]-1],str(val),['',len(str(val))])[0][:-1]
...
>>> for x in [1,12,123,1234,12345,123456,1234567,12345678]: print commafy(x)
...
1
12
123
1,234
12,345
123,456
1,234,567
12,345,678
Well, it's a one line expression, but it _is_ ugly.
Couldn't leave it at that. This one's an actual one-liner on my screen ;-)
>>> def commafy(val): return val<1000 and str(val) or commafy(val/1000)+','+commafy(val%1000)
...
>>> for x in [1,12,123,1234,12345,123456,1234567,12345678]: print commafy(x)
...
1
12
123
1,234
12,345
123,456
1,234,567
12,345,678
To handle negative numbers is a little longer:
>>> def cfy(val):
... return val<0 and '-'+cfy(abs(val)) or val<1000 and str(val) or cfy(val/1000)+','+cfy(val%1000)
...
>>> for x in [1,12,123,1234,12345,123456,1234567,12345678]: print '%12s %12s' % (cfy(x),cfy(-x))
...
1 -1
12 -12
123 -123
1,234 -1,234
12,345 -12,345
123,456 -123,456
1,234,567 -1,234,567
12,345,678 -12,345,678
Regards,
Bengt Richter
More information about the Python-list
mailing list