Reputation: 93
I feel confident that the logic of the code is correct, however, I come across keyError: 0.
def romanToInt(s: str) -> int:
roman_table = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
result = 0
for numeral in range(len(s)):
if (
numeral + 1 < len(s)
and roman_table[s[numeral]] < roman_table[s[numeral + 1]]
):
result -= roman_table[numeral]
else:
result += roman_table[numeral]
return result
romanToInt("MCMXCIV")```
Below is the error in the terminal
```$ python to_roman_numeral_converter.py
Traceback (most recent call last):
File "C:Users\XYZ\dev\repos\roman_numeral\to_roman_numeral_converter.py", line 14, in <module>
romanToInt("MCMXCIV")
File "C:\Users\XYZ\dev\repos\roman_numeral\to_roman_numeral_converter.py", line 6, in romanToInt
if numeral + 1 < len(s) and roman_table[numeral] < roman_table[numeral + 1]:
KeyError: 0
Not sure why it is not recognising roman_table value [numeral]?
Any help here is appreciated.
Upvotes: 1
Views: 60
Reputation: 93
I manged to find out the problem
def romanToInt(s: str) -> int:
roman_table = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
result = 0
for numeral in range(len(s)):
if (
numeral + 1 < len(s)
and roman_table[s[numeral]] < roman_table[s[numeral + 1]]
):
result -= roman_table[s[numeral]]
else:
result += roman_table[s[numeral]]
return result
romanToInt("MCMXCIV")
I was not accessing the value S
Upvotes: 1