using python Write a client function parenthesesMatch that given a string contai
ID: 3662560 • Letter: U
Question
using python
Write a client function parenthesesMatch that given a string containing only the characters for parentheses, braces or curly braces, i.e., the characters in ’([{}])’, returns True if the parentheses, brackets and braces match and False otherwise. Your solution must use a Stack. For, example:
>>> parenthesesMatch('(){}[]')
True
>>> parenthesesMatch('{[()]}')
True
>>> parenthesesMatch('((())){[()]}')
True
>>> parenthesesMatch('(}')
False
>>> parenthesesMatch('({])')
False
>>> parenthesesMatch('((())')
False
>>> parenthesesMatch('(()))')
False
>>> Hint: It is not sufficient to just count the number of opening and closing marks. But, it is easy to write this as a simple application of the Stack class. Here is an algorithm:
Create an empty stack.
Iterate over the characters in the given string:
If the character is one of opening marks(,[,{ push it on the stack.
If the character is one of the closing marks ),],} and the stack is empty, then there were not enough preceding opening marks, so return False.
If the character is a closing mark and the stack is not empty, pop an (opening) mark from the stack. If they are not of the same type, ie., ( and ) or [ and ] or { and }, return False, if they are of the same type, move on to the next char.
Once the iteration is finished, you know that the parentheses match if and only if the stack is empty.
Explanation / Answer
def parenthesesMatch(s):
stack = []
res = True
i = 0;
for token in s:
if token in '({[':
stack.append(token)
elif token in ')}]':
if (len(stack) == 0):
return False
else:
l = stack.pop()
if (token == ')' and l !='('):
return False
elif (token == '}' and l !='{'):
return False
elif (token == ']' and l !='['):
return False
i = i+1
if (len(stack) != 0):
res = False
if (res == False):
return False
else:
return True
print parenthesesMatch('(){}[]')
print parenthesesMatch('{[()]}')
print parenthesesMatch('((())){[()]}')
print parenthesesMatch('(()))')
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.