"number-in-base" ``oneliner''

Andrea Griffini agriff at tin.it
Mon Nov 1 09:07:30 EST 2004


On Mon, 01 Nov 2004 11:06:24 +0100, Irmen de Jong
<irmen at -NOSPAM-REMOVETHIS-xs4all.nl> wrote:

>Andrea Griffini wrote:
>
>> roman = lambda x: "".join(["".join(map(lambda c: "IVXLCDM"[int(c)
>> +2*N],"/0/00/000/01/1/10/100/1000/02".split("/")[x//10**N % 10]))
>> for N in (3, 2, 1, 0)])
>
>This rocks!! I'm still trying to understand how it works though :)

The idea is to use the pattern

  "", "0", "00", "000", "01", "1", "10", "100", "1000", "02"

where every character listed above is an offest in

  "IVX", "XLC", "CDM", "M??"

For example applying the offsets to the first group you get:

  "", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"

i.e. the roman numbers for 0..9; and applying it to the second

  "", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC",

i.e. 0, 10, 20, ... 90.

I just used "split" and string indexing instead of regular
lists because the code becomes smaller (and more readable
than a mess of quotes and commas).

The rest is a loop on the thousands, the hundreds, the tens
and the units of the number and the joins needed to glue
all the pieces into a resulting string.

Andrea




More information about the Python-list mailing list