Python阶乘栈实现中判空条件错误引发IndexError问题咨询
为什么
stack is not None和len(stack) > 0在栈判空时效果不同? 先看两段实现阶乘的Python代码:
报错的代码:
def factorial_stack(n): stack = [] while n > 0: stack.append(n) n -=1 result = 1 while stack is not None: result *= stack.pop() return result
运行时会触发报错:IndexError: pop from empty list
正常运行的代码:
def factorial_stack2(n): stack = [] while n > 0: stack.append(n) n -= 1 result = 1 #while stack is not None: while len(stack) >0: result *= stack.pop() return result
两者的核心差异就在栈的判空条件上,你误以为stack is not None和len(stack) >0作用相同,其实完全是两回事:
stack is not None是在判断变量stack是否指向None这个特殊对象。但空列表[]是一个实实在在的列表对象,和None根本不是一回事,所以这个条件永远为True——哪怕栈被pop成空列表,循环也不会停。当栈空了之后继续执行stack.pop(),自然就触发了空列表不能pop的索引错误。len(stack) >0是直接判断列表里有没有元素:当栈里还有元素时长度大于0,循环继续;元素被pop完后长度为0,循环终止,不会再执行pop操作,所以不会报错。
另外补充个小技巧:Python里空列表在布尔上下文里会被视为False,所以你也可以直接写while stack:来代替len(stack) >0,效果完全一样,代码更简洁。
内容的提问来源于stack exchange,提问作者Sonu Gupta
相关产品推荐
相关产品推荐

