Reputation:
I have code below that basically takes a list of temperatures for each day, e.g. T = [30,50,99,44,55,33,99] and returns a list of the same length with each input indicating how many days one must wait until a warmer day occurs. So for this example, the output would be [1,1,0,1,2,1,0]. If there is no warmer day ahead, we simply insert 0.
Constraints: the length of temperatures will be in the range [1, 30000]. Each temperature will be an integer in the range [30, 100]
def dailyTemperatures(self, T):
nxt = [float('inf')] * 102
ans = [0] * len(T)
for i in xrange(len(T) - 1, -1, -1):
#Use 102 so min(nxt[t]) has a default value
warmer_index = min(nxt[t] for t in xrange(T[i]+1, 102))
if warmer_index < float('inf'):
ans[i] = warmer_index - i
nxt[T[i]] = i
return ans
My question is for the line "warmer_index = min(nxt[t] for t in xrange(T[i]+1, 102))"; I understand it to the point where we are taking the minimum value of 102 and what? I don't get the first part of the min(). Can someone explain please?
And for the 'if statement' after it, won't this always be true, since float('inf') takes the biggest possible value?? Any explanation here would be good too thanks.
Upvotes: 0
Views: 50
Reputation: 782693
It's not the minimum of 102 and something.
xrange(T[i]+1, 102)
is a sequence of integers from T[i]+1
to 101
. These are used as the values of t
in nxt[t]
. min()
then returns the minimum of all those elements of nxt
.
nxt[t] for t in xrange(T[i]+1, 102)
is a generator expression that returns that sequence of values, and the sequence is passed to min()
to calculate the minimum.
Regarding the if
statement, it won't be true if no warmer days can be found, because all the nxt
values will be inf
. When that happens we skip the assignment to ans[i]
, leaving the 0
value that was given initially.
Upvotes: 1