Reputation: 11
In line 6(alternative 8). I am getting an error if I use value of range(lens), but if I reduce the value of range(lens-1). I am getting an error and not the correct answer.
For example, for the input "III", I should be getting the value 3, but instead I get the value 2. And for the input "MCMXCIV", I am getting the value 2294 instead of 1994.
In both instances, the last numeral is being skipped out. How to get without causing string index out of range?
And Can someone point out what's going on wrong here?
def romanToInt( s: str) -> int:
lens = len(s)
ans = 0
i = 0
while (i != lens):
#for i in range(lens):
print(i)
print(s[i])
if(s[i] == 'I' ):
if(s[i+1] == 'V'):
ans = ans + 4
i += 1
elif(s[i+1] == 'X' ):
ans = ans + 9
i += 1
else:
ans +=1
elif(s[i] == 'V' ):
ans += 5
elif(s[i] == 'X' ):
if(s[i+1] == 'L'):
ans += 40
i += 1
elif(s[i+1] == 'C'):
ans += 90
i +=1
else:
ans += 10
elif(s[i] == 'L' ):
ans += 50
elif(s[i] == 'C' ):
if(s[i+1] == 'D'):
ans += 400
i += 1
elif(s[i+1] == 'C'):
ans += 900
i +=1
else:
ans += 100
elif(s[i] == 'D' ):
ans += 500
elif(s[i] == 'M' ):
ans += 1000
i += 1
return ans
if __name__ == "__main__":
a = romanToInt("III")
print(a)
b = romanToInt("MCMXCIV")
print(b)
Upvotes: 0
Views: 281
Reputation: 11
I figured it out in a few moments. That using a check condition would help avoid the index out of range by not accessing s[i+1].
if(i != lens-1 and s[i+1] == 'variable'
Upvotes: 1
Reputation: 1609
You are trying to access an element that is not in your string when i
is the last index. To prevent index error, you need to check i
with lens-1
and run your validations if i < lens-1
. This way you can prevent i+1
index error. You also have mistakes in your code because you loop through the string, and you add 9 instead of 4 for the IV
case (4 for I
and 5 for V
).
Upvotes: 0