Write a program that uses the Stack implementation given to you in stack.py to c
ID: 3664661 • Letter: W
Question
Write a program that uses the Stack implementation given to you in stack.py to check for matching parentheses (brackets) in a Python file. There are three types of parentheses your program must check for: (), {}, and []. Your program should also count how many pairs of each type of parentheses occur. Your program should start by asking the user for the name of a file. The program must then read the file, checking if there is a matching closing parenthesis for each opening parenthesis. Finally, it will print out whether or not there was a matching closing and opening parenthesis for each type, and how many pairs of parentheses occurred.
# A Stack implementation
class Stack:
def __init__(self):
self.__items = []
def push(self, item):
self.__items.append(item)
def pop(self):
return self.__items.pop()
def peek(self):
return self.__items[len(self.__items)-1]
def is_empty(self):
return len(self.__items) == 0
def size(self):
return len(self.__items)
Explanation / Answer
def calculate(string): stack = [] pushChars, popChars = ")}]" for d in string : if d in pushChars : stack.append(d) elif d in popChars : if not len(stack) : return False else : stackTop = stack.pop() balancingBracket = pushChars[popChars.index(d)] if stackTop != balancingBracket : return False else : return False return not len(stack)Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.