Deviopath › Python

Roman Numerals Both Ways

Hard · Algorithms

Roman numerals use I=1, V=5, X=10, L=50, C=100, D=500, M=1000. Six pairs use subtraction: IV=4, IX=9, XL=40, XC=90, CD=400, CM=900. So 1994 is MCMXCIV (M + CM + XC + IV).

To convert a number, walk a list of all 13 values from largest to smallest and take each one as many times as it fits. To read a numeral, add each letter, but subtract it when the next letter is bigger.

Write roman(value) that works in both directions:

- if value is an int (1 to 3999), return its Roman numeral as a string - if value is a str (a valid numeral), return its value as an int

Next: Add Big Numbers as Strings