Reputation: 181
I am new to python. Trying to convert roman to numbers. Everything works perfect but when I input some roman terms I got index error. Please trace out the error and correct me.
def roman(x):
x=list(x)
print(x)
s=0
val=[['I',1],['V',5],['X',10],['L',50],['C',100],['D',500],['M',1000]]
val=dict(val)
while x:
a=val[x[0]]
b=val[x[1]]
print('a----',a)
print('b----',b)
if (a>=b):
s=s+a
x=x[1:]
else:
s=s+b-a
x=x[2:]
return s
x=input("Enter roman characters to convert to decimal: ")
x=x.upper()
a=roman(x)
print(a)
When I input 'IXC, IVX' these terms I got index error. Why it is not accepting 'I'. The output I got is shown:
Upvotes: 1
Views: 367
Reputation: 10612
Can you instead try the roman package:
>>> import roman
>>> roman.fromRoman('X')
10
>>> roman.fromRoman('IV')
4
>>> roman.fromRoman('V')
5
>>> roman.fromRoman('M')
1000
>>> roman.fromRoman('L')
50
>>>
As for the error, Jonathan has correctly pointed out:
>>> roman.fromRoman('IXC')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/sharad/trials/udev_env/lib/python3.5/site-packages/roman.py", line 72, in fromRoman
raise InvalidRomanNumeralError('Invalid Roman numeral: %s' % s)
roman.InvalidRomanNumeralError: Invalid Roman numeral: IXC
>>>
>>> roman.fromRoman('IVX')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/sharad/trials/udev_env/lib/python3.5/site-packages/roman.py", line 72, in fromRoman
raise InvalidRomanNumeralError('Invalid Roman numeral: %s' % s)
roman.InvalidRomanNumeralError: Invalid Roman numeral: IVX
>>>
The IndexError: list index out of range is due to:
In the while loop,
iteration#1
a = 1
b = 10
1 >= 10 => false
so, the code enters the else block:
x=x[2:] # x = ['C'] for IXC as input OR x = ['X'] for IVX as input
iteration#2
# x only has a single element
a=val[x[0]] # success
b=val[x[1]] # crashes, since x only has a single element
Upvotes: 2