Delimiter Pairing Using A Stack

Question:

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.

Asked By: JTruant

||

Answers:

With this code, the stack will never contain anything but open parentheses.

With this code, yes. But if you for example also allow {} and [], you’ll want a check there. Maybe that’s your upcoming homework, and they want to be consistent. Or it’s just because in general, you don’t just store the same value over and over again. Then you could just count up and down instead of using a stack at all. You use a stack when you want to remember different values. But In order to be sure about their motive, you’d have to ask them.

Answered By: Kelly Bundy
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.