Lesson 4 of 8 · 18 min

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:

  1. to_roman(n) turns a whole number from 1 to 3999 into Roman numerals.
  2. 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_roman only gets whole numbers from 1 to 3999.
  • from_roman only gets valid numerals in capital letters, so you do not need to check for mistakes.
  • from_roman(to_roman(n)) must give back n for 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 that i + 1 < len(text) first.
main.py
def to_roman(n):
    # TODO: build the numeral from the biggest symbols down
    return ""


def from_roman(text):
    # TODO: add up the symbols, subtracting the small ones that come before bigger ones
    return 0


print(to_roman(2026))         # should print MMXXVI
print(from_roman("MCMXCIV"))  # should print 1994

Python 3.14 runs right here in your browser. The first run downloads about 10 MB; after that it is instant.

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…