cant pass testcase with roman to numeral question

48 Views Asked by At
the code:
class Solution(object):
    def romanToInt(self, s):
     map={
         'I':1,
         'V':5,
         'X':10,
         'L':50,
         'C':100,
         'D':500,
         'M':1000
     }
     ans=0
     for i in range(len(s)):
         if s[i-1]=='I' and (s[i]=='V' or s[i]=='X'):
          ans=ans+map[s[i]]-2*map[s[i-1]]
         elif s[i-1]=='X' and (s[i]=='L' or s[i]=='C'):
          ans=ans+map[s[i]]-2*map[s[i-1]]
         elif s[i-1]=='C' and (s[i]=='D' or s[i]=='M'):
          ans=ans+map[s[i]]-2*map[s[i-1]]
         else:
           ans+=map[s[i]]
     return ans

the wrong test case "MCDXC" Output 1290 Expected 1490

i tried messing with the code to no avail, it worked with 3800 other test cases

1

There are 1 best solutions below

0
Thomas Weller On

You need to learn how to use a debugger.

To do so, use an IDE that allows debugging, e.g. PyCharm. Don't just use the command line. Such an IDE will help you with so much more! E.g. have a look at all the squiggly lines in the screenshot below.

Put a breakpoint (the red dot) as shown. The run step by step as long as every step and every intermediate value matches your expectation. In your case, you'll notice that the first line executed (ans is still 0 and i is also 0) is not to add "M" as 1000 in the else part.

Breakpoint

Instead, it jumps into an unexpected elif-clause. That's because s[i-1] is s[-1] and it will consider the last character of the string, which is "C". Therefor it will only add 800 instead of 1000, resulting in the difference of 200.

I also recommend not "messing with the code" but trying to approach it from a logical perspective. With a debugger, you can compare your understanding with what the code really does. Whenever those two views diverge, you have the opportunity of learning something.