copied the dictionary from your code, and this is the code values = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000} ans = 0 for char in s: ans = ans +values[char] length = len(s) for i in range(length - 1): sub_string = s[i:i+2] if sub_string == 'IV' or sub_string == 'IX': ans = ans -2 if sub_string == 'XL' or sub_string == 'XC' : ans = ans -20 if sub_string == 'CD' or sub_string == 'CM': ans = ans -200 return ans here i thought that for IV we earlier added 1+5=6, but we should have taken 4 similarly for IX 9, instead of 11, so i subtracted 2 from my original answer everytime IV or IX occur similarly 20 and 200 for other substrings and it gave me almost similar run time as yours
@samtaubman
4 ай бұрын
Nice work! I like your approach to the problem. I just consolidated the extra logic with the "special" characters into the dictionary but it's cool to see another way to solve it.
Пікірлер: 2