Leetcode question help

I wanted to test myself with a leetcode interview question, but I’m stuck on the first one. The question asks to turn a string of roman numerals into the integer form. I think that my problem is in the first if statement. (The answer is supposed to be 1994, but I get 3099)

class Solution: def romanToInt(self, s: str) -> int: converted_int = 0 roman_values = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000} for i in range(len(s)): if i+1 != len(s) and roman_values[s[i]] < roman_values[s[i + 1]]: converted_int += roman_values[s[i + 1]] - roman_values[s[i]] i += 1 else: converted_int += roman_values[s[i]] return converted_int solution = Solution() print(solution.romanToInt('MCMXCIV'))

My idea was that if the value of the current letter is less than that of the next letter, then you only add the value of the next letter minus that of the first letter. Say, if you have IX (9), then since I (1) is less than X (10), you only add X-I which is 9. But the way I have it written, the code adds both the value of IX and X. Is there a way to skip over the next iteration in a loop so I don’t encounter this problem? Or should I go back to the drawing board?

Your logic is sound, but the implementation needs a tweak. When you use for i in range(len(s)) you create a range object that will be iterated over. Manually changing the value of i doesn’t actually change the value i is assigned to. I know it seems like it should, but it doesn’t. You could keep your approach by initially assigning 0 to i, and then using a while loop. Another way would be to incorporate a bool that you toggle when you need to skip the next iteration.

Something like this
s = 'HhEeLlLlOl, WwOoRrLlDd!' skip_next = False result = '' for i in range(len(s)): if skip_next: skip_next = False continue if s[i].isupper(): skip_next = True result += s[i] print(result)

Ok, so the idea with skip_next is that it can be set to true, and then on the next iteration, if the skip_next check is true, all the code will do is continue to the next iteration.

I just put that into my code and it worked first try, thank you so much.

1 Like