3

This is a small code snippet which is causing my program to crash due to an infinite loop

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

where stack is a Stack object and operators is a dictionary. The below code however does not cause an infinite loop

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

My question is: Aren't these code snippets basically the same thing ? Why is one causing an infinite loop while the other isn't?

Thanks

2 Answers 2

3

The first one keeps looping through and peeking at the stack and checking whether a condition is true, but continuing. In the second one it cuts off after the condition is false

Sign up to request clarification or add additional context in comments.

1 Comment

...which means you could make them equivalent by adding an else: break in the first one.
2
while not stack.is_empty():
    if operators[stack.peek()] >= operators[character]:
        result += stack.pop()

Here, the while loop runs until stack is empty and you pop only for >=, it leaves some elements in the stack for < condition. So in order for the stack to become empty, stack.size() == number of times operators[stack.peek()] >= operators[character] is true


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

Here, you are restricting the while loop by only allowing it to continue only when >= condition is statisfied along with stack not empty.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.