Drill

ProblemsPython › warmup

Write a number in Roman numerals

mediumwarmupPython

A film credit or a chapter heading wants MCMXCIV rather than 1994.

to_roman(amount: int) → string

Solve it in the editor →

Where you start

def to_roman(amount: int) -> str:
    

Worked examples

CallResult
to_roman(1)"I"
to_roman(4)"IV"
to_roman(14)"XIV"
to_roman(1994)"MCMXCIV"

Hint

Keep the values and their symbols in one descending table, including the subtractive pairs. Then it is one greedy pass.

Reference solution in Python
def to_roman(amount: int) -> str:
    if amount < 1 or amount > 3999:
        return ''
    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')]
    n = amount
    result = ''
    for v, sym in table:
        while n >= v:
            result += sym
            n -= v
    return result

The same problem in another language

More warmup problems in Python