Loading

Simple Roman Numeral Conversion in Python

For Example, We like to convert CCXCIV to 294

# Mapping of Roman Numerals to English Digits is like this
I=1
V=5
X=10
L=50
C=100
D=500
M=1000

# We can use Dictionary in Python
R={'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}

# Actual Function to sum up the values for each roman numerals, in a line
roman=lambda x:reduce(lambda T,x:T+R[x]-T%R[x]*2,x,0)

In python, there is reduce function, that can do [1,2,3,4] => 10, 
by summing up from left to right like this (((1+2)+3)+4)

The correct answer should be , C=100, C=100, XC=90, IV=4 => 294

But when we sum up XC, X=10, C=100, oh, its becomes 110, and actual one should be 90.

No worries, 110 is the 90 + 20, and 20 is 2 times of X, isnt it? so just substract it after you sum up :-)

-T%R[x]*2 will do it for you, got it? IV will do same as 6 - 2 => 4 too :-)

so 200 + 90 + 4 will be 294 :-)

Thats the idea I got today, may be somebody already done like that before, but I can't find anything like this in Google, so this is mine.

You can download full program here at my google code page, the license for that is MIT License.


Here is the some of the test results

I 1 1 True
II 2 2 True
III 3 3 True
IV 4 4 True
V 5 5 True
VI 6 6 True
VII 7 7 True
VIII 8 8 True
IX 9 9 True
X 10 10 True
L 50 50 True
C 100 100 True
D 500 500 True
M 1000 1000 True
XXXI 31 31 True
CXLVIII 148 148 True
CCXCIV 294 294 True
CCCXII 312 312 True
CDXXI 421 421 True
DXXVIII 528 528 True
DCXXI 621 621 True
DCCLXXXII 782 782 True
DCCCLXX 870 870 True
CMXLI 941 941 True
MXLIII 1043 1043 True

# First column is Roman Numerals, 2nd is actual Values, 3rd is generate Results, 4th is checking the Result is Right or Wrong 

Cheers,
Mark


3 comments:

Unknown said...

Guru, that is grade explain :. Thanks,

Regards,

ST

Unknown said...

I very rush, grade* (great), sorry for wrong spelling.
:)

ေဘာက္တူး said...

bro, very nice program! :-)
also very nice distribution with MIT License. :-) Love it!

rgds,

က်ေနာ္ဖတ္ေသာ အျခား ဘေလာ့ / ဆိုဒ္မ်ား