class Solution:
def romanToInt(self, s: str) -> int:
dict = {
'I' : 1,
'V' : 5,
'X' : 10,
'L' : 50,
'C' : 100,
'D' : 500,
'M' : 1000
}
result = 0
tmp = 0;
i = 0
while i < len(s):
tmp = dict[s[i]];
if (i +1) < len(s) and dict[s[i]] < dict[s[i + 1]]:
tmp = dict[s[i + 1]] - dict[s[i]]
i += 1
i += 1
result += tmp;
print (result)
Asked
Active
Viewed 41 times
-2

Daniel Hao
- 4,922
- 3
- 10
- 23
-
1Do the answers to this [question](https://stackoverflow.com/questions/32557920/what-are-type-hints-in-python-3-5) help at all? – quamrana Jun 09 '22 at 11:21
-
`Solution().romanToInt("V")`; `romanToInt(self, s: str) -> int:` - `:str` and `-> int` are **type hints** - they do not have an effect on the behaviour of the function, but can be used by IDE to suggest how the method is supposed to be used. – matszwecja Jun 09 '22 at 11:24
1 Answers
0
I edited your code a little bit because you shouldn't use type keywords as variable names and to make it more readable
class Solution:
def romanToInt(self, text: str) -> int:
pairs = {
'I' : 1, 'V' : 5, 'X' : 10, 'L' : 50,
'C' : 100, 'D' : 500, 'M' : 1000
}
result = tmp = i = 0
while i < len(text):
tmp = pairs[text[i]];
if i + 1 < len(text) and pairs[text[i]] < pairs[text[i + 1]]:
tmp = pairs[text[i + 1]] - pairs[text[i]]
i += 1
i += 1
result += tmp
print(result)
solution = Solution() # initialize instance of Solution class
solution.romanToInt("XXVIII") # run the romanToInt method
ouput = 28

Alexander
- 16,091
- 5
- 13
- 29