Skip to content Skip to sidebar Skip to footer

Using Python 3 Stacks To Ensure Symbols Match In Correct Pairs And The Types Of Symbols Match As Well

def spc(sym): stk1=myStack() stkall=myStack() for i in sym: if i not in stk1: stk1.push(i) else: stkall.push(i) for j in stk

Solution 1:

These lines

if i not in stk1:

and

for j in stk1:

requires myStack to be iterable. In Python it means that it shall have an __iter__ method that returns an iterator on its objects. As you already have an internal container, the __iter__ method can be as simple as:

class myStack:
    ...
    def __iter__(self):
        return iter(self.container)

Solution 2:

To do bracket validation using a stack, we only need one stack. As we come across opening brackets, we push them onto the stack. When we come across a closing bracket, we pop the top opening bracket off the stack, and compare the two. If they are the same bracket type, we continue, otherwise the string is invalid. If we ever try to pop an empty stack, the string is invalid. If we reach the end of the string without clearing the stack, the string is invalid.

opening = '[{<('
closing = ']}>)'

d = dict(zip(opening, closing))

def validate(s):
    stack = []
    for c in s:
        if c in opening:
            stack.append(c)
        elif c in closing:
            if not stack:
                # tried to pop empty stack
                return False
            popped = stack.pop()
            if d[popped] != c:
                # bracket mismatch
                return False
    return not stack

Post a Comment for "Using Python 3 Stacks To Ensure Symbols Match In Correct Pairs And The Types Of Symbols Match As Well"