Roman Numerals
Medium · 55 XPWrite to_roman(n) converting an integer (1–3999) to a Roman numeral. Print the result for 4, 44, 1994 and 3999.
Target output
IV XLIV MCMXCIV MMMCMXCIX
Blank · autosaved
PYroman-numerals.py
Walk a value→symbol table from largest to smallest, including the subtractive pairs (900 CM, 400 CD, 90 XC, 40 XL, 9 IX, 4 IV).
def to_roman(n):
table = [(1000, "M"), (900, "CM"), (500, "D"), (400, "CD"),
(100, "C"), (90, "XC"), (50, "L"), (40, "XL"),
(10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I")]
out = ""
for value, symbol in table:
while n >= value:
out += symbol
n -= value
return out
for n in (4, 44, 1994, 3999):
print(to_roman(n))
Run your code to check it…