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
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With