romanD = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
oper = []
s = input('roman')
i = 0
class Solution(object):
def romanToInt(self, s):
rtype = int
# for i in range(len(s)-1):
for j in range(1, len(s)):
i = 0
if i >= len(s):
break
elif romanD[s[i]] < romanD[s[j]]:
oper.append(-1 * romanD[s[i]])
elif romanD[s[i]] >= romanD[s[j]]:
oper.append(romanD[s[i]])
i = 1
oper.append(romanD[s[len(s) - 1]])
return sum(oper)
b = Solution()
print(b.romanToInt(s))
I go step by step with the runs:
L returns 50
LV returns 55
LVI returns 101
I don't know where I'm going wrong. For some reason, at 3 digits, it adds the first value twice and ignores the second value.
CodePudding user response:
If you uncomment for i in range(len(s)-1):
out, you get 56 ;)
romanD = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
oper = []
s = input('roman')
i = 0
class Solution(object):
def romanToInt(self, s):
rtype = int
for i in range(len(s)-1):
for j in range(1, len(s)):
if i >= len(s):
break
elif romanD[s[i]] < romanD[s[j]]:
oper.append(-1 * romanD[s[i]])
elif romanD[s[i]] >= romanD[s[j]]:
oper.append(romanD[s[i]])
i = 1
oper.append(romanD[s[len(s) - 1]])
return sum(oper)
b = Solution()
print(b.romanToInt(s))
CodePudding user response:
This happens because i = 0
is in the for j in range()
loop, so i
will always be 0
. To fix this just put i = 0
before the loop like this:
def romanToInt(self, s):
rtype = int
# for i in range(len(s)-1):
i = 0 # <---- here :)
for j in range(1, len(s)):
if i >= len(s):
break
elif romanD[s[i]] < romanD[s[j]]:
oper.append(-1 * romanD[s[i]])
elif romanD[s[i]] >= romanD[s[j]]:
oper.append(romanD[s[i]])
i = 1
oper.append(romanD[s[len(s) - 1]])
return sum(oper)
CodePudding user response:
Magically, I still don't know how removing i fixed everything. But it did.
romanD = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
oper = []
s = input('roman')
class Solution(object):
def romanToInt(self, s):
rtype = int
for j in range(len(s)):
if j 1 >= len(s):
break
elif romanD[s[j]] < romanD[s[j 1]]:
oper.append(-1 * romanD[s[j]])
elif romanD[s[j]] >= romanD[s[j 1]]:
oper.append(romanD[s[j]])
oper.append(romanD[s[len(s) - 1]])
return sum(oper)
b = Solution()
print(b.romanToInt(s))