Perhaps consider something like the following-
current_period = self.current_period - (self.current_period % 7)
MIN_VALUE = current_period - 7 * MAX_VALUE
return self.multiplier * sum(value * self.lookup[key][self._get_age(key)]
for key, value in input_dict[self.state][self.city].iteritems()
if MIN_VALUE < key < current_period
)
Here I pull the multiplication by self.multiplier
out of the loop, and replace the comparison 0 < age < MAX_VALUE
with an equivalent comparison of precomputed values, obtained by substituting age
with your _get_age()
method described in the comments and solving for key
. This allows us to skip the function call + extra computations for cases where age <= 0 or age >= MAX_VALUE
, and incurs no extra cost (save for computing the 2 variables outside the loop) over the original if 0 < age < MAX_VALUE
. Additionally, this allows us to make use of the builtin sum()
function, which is typically faster than summing via a for loop, but without creating a separate generator as in qxz's answer.
Note that I assume (self.current_period - period)
in your _get_age()
method is an integer, and so / 7
floors the result in Python-2.x. If this is not the case, remove the - (self.current_period % 7)
from the current_period
assignment for equivalent functionality.