100 XP

30. Roman numerals

Advanced dictionaries strings

Roman numerals write numbers with seven letters:

Letter I V X L C D M
Value 1 5 10 50 100 500 1000

Usually the letters go from largest to smallest, and you add up their values: VIII is 5 + 1 + 1 + 1 = 8. But when a letter is worth less than the letter after it, it is taken away instead of added: IV is 5 - 1 = 4. This happens in six pairs: IV (4), IX (9), XL (40), XC (90), CD (400) and CM (900).

Write a function roman_to_int(numeral) that takes a Roman numeral as a string and returns its value as a whole number.

Example 1

Inputnumeral = "XIV"
Output14
ExplanationX = 10, then IV = 4.

Example 2

Inputnumeral = "MCMXCIV"
Output1994
ExplanationM = 1000, CM = 900, XC = 90, IV = 4.

Example 3

Inputnumeral = "XLII"
Output42
ExplanationXL = 40, then II = 2.

Constraints

  • numeral has 1 to 15 characters, all capital letters from the table.
  • It is a valid Roman numeral for a number from 1 to 3999.

Submit also runs 6 more tests you can't see.

Practises Dictionaries (lesson 11).

Code
def roman_to_int(numeral):
    """Return the value of a Roman numeral.

    numeral: str, a valid numeral such as "XIV", for a
        number from 1 to 3999
    Returns: int, its value, such as 14
    """
    # Write your code here
    pass