Question
USE PYTHON3; DO NOT IMPORT ANY PACKAGES Write a parentheses checker using the Stack you just implemented. The checker will look for three kinds of
USE PYTHON3; DO NOT IMPORT ANY PACKAGES
Write a parentheses checker using the Stack you just implemented. The checker will look for three kinds of parentheses: `{}`, `[]` and `()`, and ignore all other characters. This function will take a string expression, and return True if all parentheses pairs are balanced.
To consider an expression balanced, every open parenthesis can be paired with a close parenthesis of the same kind, and vice versa. Whenever the function encounters a close parenthesis, it will judge whether this close parenthesis has the same type as the nearest open parenthesis to its left. The function will return False if the function cannot find a nearest open parenthesis to its left, or the open parenthesis found is of different type. The function will also return False if some open parentheses are not matched after checking the entire expression.
You must use the Stack you just implemented to solve this problem.
Here is the implemented Stack code the problem is talking about:
class Collection: """ A class to abstract the common functionalities of Stack and Queue. This class should not be initialized directly. """
def __init__(self): """ Constructor. """ self.items = [] self.num_items = 0
def size(self): """ Get the number of items stored. """ return self.num_items
def is_empty(self): """ Check whether the collection is empty. """ return self.num_items == 0
def clear(self): """ Remove all items in the collection. """ self.items = [] self.num_items = 0
class Stack(Collection):
def push(self, item): """ Push `item` to the stack. """ if item == None: raise ValueError("item cannot be None") self.items.append(item) self.num_items += 1
def pop(self): """ Pop the top item from the stack. """ if self.num_items == 0: return None self.num_items -= 1 return self.items.pop()
def peek(self): """ Peek the top item. """ if self.num_items == 0: return None return self.items[-1]
def __str__(self): """ Return the string representation of the stack. """ strings = map(str, self.items) if self.num_items == 0: return ("(bottom) " + "(top)") return ("(bottom) " + " -- ".join(strings) + " (top)")
THE CODE:
def parentheses_checker(expression):
"""
>>> parentheses_checker("(((]})")
False
>>> parentheses_checker("(")
False
>>> parentheses_checker("(){}[]")
True
"""
# YOUR CODE GOES HERE #
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started