Python for循环range逆序参数与while stack判断语法疑问
from typing import List def dailyTemperatures(temperatures: List[int]) -> List[int]: temp_count = len(temperatures) ans = [0]*temp_count stack = [] idx_stack = [] for idx in range(temp_count-1,-1,-1): // first point temperature = temperatures[idx] last_temp_idx = 0 while stack: // second point last_temp = stack[-1] last_temp_idx = idx_stack[-1] if last_temp <= temperature: stack.pop() idx_stack.pop() else: break if len(stack) == 0: stack.append(temperature) idx_stack.append(idx) ans[idx] = 0 continue stack.append(temperature) idx_stack.append(idx) ans[idx] = last_temp_idx-idx return ans
问题1解答
Python内置的range函数传入3个参数时,语法规则为range(起始值, 终止值, 步长),遍历逻辑遵循左闭右开:生成的序列包含起始值,不包含终止值,每次按步长的数值增减。
对应代码里的range(temp_count-1, -1, -1):
- 第一个参数
temp_count-1是遍历起始索引:温度数组的索引范围是0到len(temperatures)-1也就是temp_count-1,这段逻辑要从数组最后一位倒着往前遍历,所以起始值设为它。 - 第二个参数
-1是遍历终止值:因为左闭右开的规则,要让遍历能覆盖到索引0,就得把终止值设为0的前一位也就是-1,这样遍历到0之后下一个值是-1,会触发终止条件,不会继续。 - 第三个参数
-1是步长:代表每次循环索引减1,实现倒序遍历的效果。
你理解的每次循环索引递减1是对的,两个-1分别对应终止值和步长,作用完全不同。
问题2解答
Python里所有容器类型(列表、字典、元组等)做布尔判断时,空容器会被判定为False,非空容器会被判定为True。
所以while stack:的判断逻辑是:当stack不为空时,执行循环体内的代码,如果stack是空的,会直接跳过整个while循环,和你猜测的逻辑刚好相反。
内容的提问来源于stack exchange,提问作者David Kim
相关产品推荐
相关产品推荐

