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

forjin 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:

classmyStack:
    ...
    def__iter__(self):
        returniter(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))

defvalidate(s):
    stack = []
    for c in s:
        if c in opening:
            stack.append(c)
        elif c in closing:
            ifnot stack:
                # tried to pop empty stackreturnFalse
            popped = stack.pop()
            if d[popped] != c:
                # bracket mismatchreturnFalsereturnnot stack

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