Roman Numerals
Completed
Read a Roman numeral (I, V, X, L, C, D, M) and print its value. A smaller symbol before a larger one is subtracted (IV = 4).
Input
One valid numeral up to 3999.
Output
The integer value.
Example
Input
XIV
Output
14
Editor
Python
Hints
Map each symbol to its value with a dict.
Subtract a value when the next symbol is larger.
Solution explanation
A dict turns a chain of if statements into one lookup.
Show solution
values = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
s = input()
total = 0
for i, ch in enumerate(s):
v = values[ch]
if i + 1 < len(s) and v < values[s[i + 1]]:
total -= v
else:
total += v
print(total)