Challenge: Roman numerals, both ways
Arjun is visiting a museum in Port Louis. The old clock on the wall shows IV and IX, a foundation stone says MDCCCLXIV, and the film in the cinema room ends with MMXXVI. He wants a little program to translate.
Roman numerals use seven symbols:
| Symbol | I | V | X | L | C | D | M |
|---|---|---|---|---|---|---|---|
| Value | 1 | 5 | 10 | 50 | 100 | 500 | 1000 |
Symbols are written from biggest to smallest and added up: MMXXVI is 1000 + 1000 + 10 + 10 + 5 + 1 = 2026.
The twist: a symbol is never repeated four times. Instead, a smaller symbol before a bigger one is subtracted. There are exactly six of these pairs:
| IV | IX | XL | XC | CD | CM |
|---|---|---|---|---|---|
| 4 | 9 | 40 | 90 | 400 | 900 |
So 1994 is M + CM + XC + IV = MCMXCIV.
Your task
Write two functions:
to_roman(n)turns a whole number from 1 to 3999 into Roman numerals.from_roman(text)turns valid Roman numerals back into a number.
to_roman(2026) # "MMXXVI"
to_roman(1994) # "MCMXCIV"
to_roman(4) # "IV"
from_roman("XIV") # 14
from_roman("MCMXCIV") # 1994
Rules
to_romanonly gets whole numbers from 1 to 3999.from_romanonly gets valid numerals in capital letters, so you do not need to check for mistakes.from_roman(to_roman(n))must give backnfor every number from 1 to 3999.
Tips
- For
to_roman, make a list of 13 value/symbol pairs from biggest to smallest, with the six subtractive pairs in their places:[(1000, "M"), (900, "CM"), (500, "D"), (400, "CD"), ...]. Then take away the biggest value that fits, again and again. - For
from_roman, a dictionary like{"I": 1, "V": 5, "X": 10, ...}gives each symbol's value. Look at each symbol together with the next one: if the next is bigger, subtract this one, otherwise add it. text[i + 1]fails past the end of the string, so check thati + 1 < len(text)first.