I wrote this code (spoilers for LeetCode problem 13):
roman_numbers = [('I', 1), ('V', 5), ('X', 10), ('L', 50), ('C', 100), ('D', 500), ('M', 1000)]
class Solution:
def get_value(self, number):
return dict(roman_numbers)[str(number)]
def romanToInt(self, s: str) -> int:
result = 0
letter_list = list(letter for letter in s)
for letter in s:
try:
if self.get_value(letter_list[0]) >= self.get_value(letter_list[1]):
result += self.get_value(letter_list[0])
letter_list.remove(letter_list[0])
else:
result -= self.get_value(letter_list[0])
letter_list.remove(letter_list[0])
except IndexError:
result += self.get_value(letter_list[0])
return result
The code works, but I wanted to refactor it to make it less repetitive. The pattern self.get_value(letter_list[x])
appears many times, so I'd like to make a variable that stores a result like letter_list.remove(letter_list[0])
, so I can write code like
if letter0 >= letter1:
result += letter0
But since the letter_list
will change, I need to make sure that the variables are updated when necessary.
I tried creating the variable inside the for
loop, so that it updates every time through the loop:
for letter in s:
letter0 = self.get_value(letter_list[0])
letter1 = self.get_value(letter_list[1])
...
However, I'm not sure that I've properly understood what's going on.
What exactly causes the variables to update? Is it because the code is inside a function? Is the variable getting re-created each time through the loop?
And is this correct logic - will the variables be up-to-date when they are used? In the past I've had many problems with variable values getting out of sync.
What makes the variable change is the assignment operation:
letter0 = ...
Whatever is to the right of the assignment (=, += etc) is evaluated/executed first, then the result is stuffed in the variable. But no, in Python variables do not evaporate when you reach the bottom of the loop (scope) they are defined in. The next assignment simply replaces what the variable referred to before.