30. Roman numerals
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
numeral = "XIV"14Example 2
numeral = "MCMXCIV"1994Example 3
numeral = "XLII"42Constraints
numeralhas 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).
- Put the letters' values in a dictionary:
{"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}. - Look at each letter together with the one after it. A letter worth less than the next one, such as the
IinIVor theCinCM, is taken away; every other letter is added. - Loop with
for i, letter in enumerate(numeral):and checki + 1 < len(numeral)before you readnumeral[i + 1]: the last letter has no next one, and is always added.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
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
Run your code to see how it does on the test cases, or Submit to check every test.