奇怪的是while循环导致无限循环

时间:2015-09-07 11:41:50

标签: python while-loop

这是一个小代码片段,导致我的程序因无限循环而崩溃

while not stack.is_empty():
    if operators[stack.peek()] >= operators[character]:
        result += stack.pop()

其中stack是Stack对象,operator是字典。 但是下面的代码不会导致无限循环

while not stack.is_empty() and operators[stack.peek()] >= operators[character]:
    result += stack.pop()

我的问题是:Aren这些代码片段基本上是一回事吗?为什么一个引起无限循环而另一个不是?

由于

2 个答案:

答案 0 :(得分:3)

第一个不断循环并窥视堆栈并检查条件是否为真,但仍在继续。在第二个中它在条件为假之后切断

答案 1 :(得分:2)

while not stack.is_empty():
    if operators[stack.peek()] >= operators[character]:
        result += stack.pop()

这里,while循环运行直到stack为空并且只为>=弹出,它会在堆栈中留下<条件的一些元素。所以为了使堆栈变空,stack.size()==次operators[stack.peek()] >= operators[character]true

while not stack.is_empty() and operators[stack.peek()] `>=` operators[character]:
    result += stack.pop()

在这里,你只是限制while循环,只允许它在>=条件得到满足且堆栈不为空的情况下继续。

相关问题