执行此代码后堆栈是否为空?



我正在为那段代码而苦苦挣扎。我不确定代码执行时堆栈是否会为空。我错过了什么吗?

s1 = Stack()
q = Queue()
s1.push(1)
s1.push(2)
s1.push(3)
while not s1.isEmpty():
q.enqueue(s1.pop())
print(q.dequeue(), end = ' ')
print(q.dequeue(), end = ' ')
print(q.dequeue(), end = ' ')

是的,执行此代码后堆栈将为空。

这很容易证明:while循环的条件是not s1.isEmpty(),所以如果堆栈不为空,那么循环继续运行。因此,如果到达循环后的 print 语句,一定是因为条件变为 falsenot s1.isEmpty(),因此堆栈为空。然后在该点和程序结束之间没有其他内容被推送到堆栈,因此堆栈保持为空。

更一般地说,只要你有一个带有某个条件的while循环,并且该循环没有允许它因其他原因终止的break语句,那么我们可以断言,只要到达循环之后的行,条件肯定是假的:

while condition:
# no break statements in the loop
# ...
# whenever this line of code is reached, the condition must be false
assert not condition

这是一种简单但非常强大的推理循环程序行为的方法。

最新更新