I am currently taking a Data Structures & Algorithms course, and while learning about Stacks, the instructor has presented a function called check_parens(), which takes an expression as input and checks to see if the parentheses in the expression are well-balanced.
The function is as follows:
def check_parens(expr):
s = Stack()
for c in expr:
if c == '(':
s.push(c)
elif c == ')':
if s.empty() or s.pop()!='(':
return False
return s.empty()
I understand that this function works properly, but I do not understand why "s.pop() != '('" is included in the inner if condition other than to pop off the current element in the stack should it not already be empty. Otherwise, what is the point in checking if an element in the stack is not equal to '('? With this code, the stack will never contain anything but open parentheses.