Using Python stack to implement bracket matching algorithm

Keywords: Python Programming

Using Python list to realize the structure of a stack, and then using stack to realize the algorithm of bracket matching. The so-called bracket matching refers to that in programming language, brackets appear in pairs, the first left bracket corresponds to the last right bracket, and the last left bracket corresponds to the latest right bracket, which conforms to the characteristics of stack

Write a stack class: stack.py

class Stack:
    def __init__(self):
        self.items = []

    def is_Empty(self):
        return self.items == []

    def push(self, item):
        self.items.append(item)

    def pop(self):
        return self.items.pop()

    def peek(self):
        return self.items[len(items)-1]
    def size(self):
        return len(self.items)

The algorithm program to achieve bracket matching:

from stack import Stack
def parChecker(symbolString):
    s = Stack()
    balanced = True
    index = 0
    while index < len(symbolString) and balanced:
        symbol = symbolString[index]
        if symbol == "(":
            s.push(symbol)
        elif symbol == ")":
            if s.is_Empty():
                balanced = False
            else:
                s.pop()

        index += 1
    if balanced and s.is_Empty():
        return True
    else:
        return False

print(parChecker("(((2356)))"))

Output results:
True
Retest

print(parChecker("(()))"))

Output False

extend

Can match multiple brackets, {}, []
Just a little code change:

from stack import Stack

def parChecker(symbolString):
    s = Stack()
    balanced = True
    index = 0
    while index < len(symbolString) and balanced:
        symbol = symbolString[index]
        if symbol in "({[":
            s.push(symbol)
        elif symbol in ")}]":
            if s.is_Empty():
                balanced = False
            else:
                s.pop()

        index += 1
    if balanced and s.is_Empty():
        return True
    else:
        return False

print(parChecker("[(({fdf}))]"))

Posted by digitalecartoons on Tue, 05 Nov 2019 07:00:49 -0800