A string is considered to have valid parentheses if there are an equal number of
ID: 3861475 • Letter: A
Question
A string is considered to have valid parentheses if there are an equal number of opening/closing brackets and each closing bracket - e.g., ), }, or] - matches the most recent, unmatched opening bracket - e.g., (, {, or [. For example: (({})) is valid {[{()}]> is valid (){}[] is valid ((}) is invalid Checking the validity of parentheses is important in verifying the validity of programming code and mathematical statements. Create a new Python file called validator.py with a single function called invalid(string). This function will take a single string that can consist of any characters and use the stack implementation from problem 1A to determine if the parentheses are valid or not. the function will return True if the string has valid parentheses and False otherwise. Your function only needs to consider the three types of bracket characters mentioned above - the remaining characters, which could represent code, numbers, arithmetic operators, etc., can be ignored. You can use the validatorchecker.py file from cu Learn to check whether your function is working correctly. If you are having trouble figuring out how to solve the problem, consider how you would validate each of the sets of brackets above using the stack operations available from problem 1A.Explanation / Answer
class Stack(object):
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[-1]
def isEmpty(self):
return len(self.items) == 0
def isValid(string):
stack =Stack()
for ch in string :
if(ch=='{' or ch=='(' or ch=='[' ):
stack.push(ch)
if(ch=='}' ):
close = stack.pop()
if(close != '{'):
return False
if(ch==']'):
close = stack.pop()
if(close != '['):
return False
if(ch==')'):
close = stack.pop()
if(close != '('):
return False
if(stack.isEmpty()):
return True
return False
#MAIN
print ""{}{}{()" is valid ="+str(isValid("{}{}{()"))
print ""{}{}{()}" is valid ="+str(isValid("{}{}{()}"))
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.