Here is my code for Roman to Integer problem I can not understand why the for loop is only working on the first two elements.
class Solution(object):
def romanToInt(self, S):
ran = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
sum = 0
for i in S:
num = ran[i]
num2 = ran[S[S.index(i) 1]]
if num >= num2:
sum = num num2
else:
sum = num - num2
return sum
CodePudding user response:
return will break for loop when excute put it after for loop and sumlogic is wrong
def romanToInt(S):
ran = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
sum = 0
for i in range(len(S)-1):
num1=ran[S[i]]
num2=ran[S[i 1]]
if num1>=num2:
sum=sum num1
else:
sum=sum-num1
return sum ran[S[-1]]
CodePudding user response:
It's because the "return" is inside the for loop, so when the first loop ends, the program ends, to fix it just take the "return" out of your for loop.
def romanToInt(self, S):
for i in S:
.......
.......
return sum