Hackbright Code Challenges

Roman Numerals

Roman Numerals

Whiteboard

Harder

Challenge

Medium

Concepts

General, Math

Download

roman-numerals.zip

Solution

Roman Numerals: Solution


Write a method that converts an integer to its Roman numeral equivalent.

For reference, these are the building blocks for how we encode numbers with Roman numerals:

Decimal

Roman

1

I

5

V

10

X

50

L

100

C

500

D

1,000

M

For example:

>>> to_roman(5)
'V'

>>> to_roman(267)
'CCLXVII'

Important: You should convert to “old-school Roman numerals”, where subtraction isn’t used. So, for exmple, 4 is “IIII” and 9 is “VIIII”. You may be more used to a different style, where subtraction is used, as 4 would be “IV” and 9 would be “IX”. This is not what we want here (though it’s a good, but much harder challenge).

For example:

>>> to_roman(99)
'LXXXXVIIII'

We given you a file, roman_numerals.py, with a method, to_roman:

def to_roman(num):
    """Converts positive integers to Roman numeral equivalent using Old-school style."""

    if num != int(num) or num > 4999 or num < 1:
        raise ValueError("Cannot convert")

However, this method is unimplemented.