Home > database >  I have tested my code on pyCharm and it works, but on Leetcode it gives me a KeyError and doesn'
I have tested my code on pyCharm and it works, but on Leetcode it gives me a KeyError and doesn'

Time:12-26

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))

The error:

KeyError: '"'
    elif romanD[s[j]] < romanD[s[j 1]]:
Line 12 in romanToInt (Solution.py)
    print(b.romanToInt(s))
Line 21 in <module> (Solution.py)

I specifically wrote the 'if then break' part to not go out of the range of input but to no vain.

CodePudding user response:

I fixed it by adding

s = s.replace('"','')

! Thanks for the ideas

CodePudding user response:

Since the word you entered is not in the romanD list and there will be uppercase and lowercase matching, I made a few changes in the code, you can use it.

romanD = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
oper = []
s = input('roman').upper().split('"')
s=s[0]

class Solution(object):
    def romanToInt(self, s):
        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]])
        try:
            oper.append(romanD[s[len(s) - 1]])
        except:
            print('the word you entered is incorrect',s)
        return sum(oper)


b = Solution()
print(b.romanToInt(s))
  • Related