Free lab Real Python 3. Zero installs. Your code stays in this browser. Open the playground

Roman Numerals

Medium · 55 XP

Write 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
Run your code to check it…
Guide

How to approach Roman Numerals

Roman numerals are built greedily: take the biggest symbol that still fits, subtract its value, and repeat. The only subtlety is the subtractive forms such as IV for 4 and CM for 900.

The clean way to handle them is to stop treating them as exceptions. Put the six subtractive pairs in the value table alongside the seven ordinary symbols, sorted from 1000 down to 1, and the same greedy loop produces correct numerals for every number from 1 to 3999.

Worked through on this data

  1. 1994: M fits (1000), leaving 994. CM fits (900), leaving 94.
  2. XC fits (90), leaving 4. IV fits (4), leaving 0.
  3. Joined: MCMXCIV. The same process gives IV for 4, XLIV for 44 and MMMCMXCIX for 3999.

Common mistakes

  • Leaving out the subtractive pairs gives IIII for 4 and DCCCC for 900.
  • Putting the table in the wrong order (for example 500 before 900) lets D grab 1994 first and produces nonsense.
  • Using if instead of while for each symbol writes 3 as I instead of III.

Time and space

The table has 13 entries and no numeral up to 3999 is longer than 15 symbols, so the work is bounded: O(1) for this input range.

Where this shows up

Greedy selection from a sorted table is how change-making in tills works, and how human-readable durations such as "2h 15m" and file sizes such as "3.4 MB" are formatted.

Take it further

Write from_roman(s): add each symbol's value, but subtract it when a larger symbol follows it. Check that every number from 1 to 3999 round-trips.

Your next ten minutes

Write Python that does something useful.

Start free. No install, no card, no passive video marathon.

Start learning free → Explore the path