Tuesday, December 1, 2009

Roman numerals - update

After I posted about converting between decimal and Roman numerals here, I came upon a simpler way to handle the forward direction, from decimal to Roman.

Rather than divide sequentially by 1000, 100, and finally 10, we include 900, 500, 400 etc. in our list of divisors, and modify the symbols to be saved accordingly. This idea is included in the Python Cookbook. I'm not sure who thought it up first, but it's a nice trick.

Here is the code:


def decimalToRoman2(n):
divs = [1000, 900, 500, 400,
100, 90, 50, 40,
10, 9, 5, 4, 1]
symbols = ['M', 'CM', 'D', 'CD',
'C', 'XC', 'L', 'XL',
'X', 'IX', 'V', 'IV', 'I']
vals = list()
for i,d in enumerate(divs):
x = n/d
if x:
vals.append(symbols[i]*x)
n = n%d
return ''.join(vals)