minimanimoh / Udacity_DS-A

0 stars 0 forks source link

DS&A - 2. Data Structures - Lesson 2. Balanced Parentheses Exercise #16

Open minimanimoh opened 3 years ago

minimanimoh commented 3 years ago
class Stack:
    def __init__(self):
        self.items = []

    def size(self):
        return len(self.items)

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

    def pop(self):
        if self.size()==0:
            return None
        else:
            return self.items.pop()

def equation_checker(equation):

    # TODO: Initiate stack object
    stack_open = Stack()
    stack_close = Stack()

    # TODO: Interate through equation checking parentheses
    for char in equation:
        if char == "(":
            stack_open.push(char)
        elif char == ")":
            stack_close.push(char)

    # TODO: Return True if balanced and False if not
    if stack_open.size() == stack_close.size():
        return True
    else:
        return False
minimanimoh commented 3 years ago

^ my code

minimanimoh commented 3 years ago
def equation_checker(equation):

    stack = Stack()

    for char in equation:
        if char == "(":
            stack.push(char)
        elif char == ")":
            if stack.pop() == None:
                return False

    if stack.size() == 0:
        return True
    else:
        return False
minimanimoh commented 3 years ago

answer