Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weird while loop causes infinite loop

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

like image 464
Jacklin213 Avatar asked Jan 18 '26 04:01

Jacklin213


2 Answers

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

like image 78
Rohan Jhunjhunwala Avatar answered Jan 20 '26 19:01

Rohan Jhunjhunwala


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.

like image 32
Barun Avatar answered Jan 20 '26 18:01

Barun