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

I

Irmen de Jong

Andrea said:
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 :)
--Irmen
 
A

Andrea Griffini

Andrea said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,682
Members
48,796
Latest member
Greg L.

Latest Threads

Top