Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Programming Language: Python IMPORTANT: For this exercise, you will be defining

ID: 3871515 • Letter: P

Question

Programming Language: Python

IMPORTANT: For this exercise, you will be defining a function that USES the Stack ADT. A stack implementation is provided to you as part of this exercise - you should not use your own Stack class. Instead, simply use the functions: Stack(), push(), pop() and is_empty() where necessary inside your function definition.

For this exercise, you must write a function called balanced_brackets(). This function will be passed a string as an input, and you must check that any parentheses or angled brackets in the string, that is: '(', '<', ')' and '>', are correctly balanced.

Here are a few examples of strings where brackets are correctly balanced:

a(ef)g

abcde

a(b)c

and here are a few examples where the brackets are not balanced:

ab(cde>

a)def

ab)c

Your balanced_brackets() function should return True if the input string is balanced, and False otherwise. Remember, you can assume that an implementation of the Stack ADT is available to you. It is likely that your function definition will begin as follows:

For example:

Test Result
  print(balanced_brackets('()(())()'))  
  True  
  print(balanced_brackets('xz'))  
  False  

Explanation / Answer

Below is the python code that does the task

def do_parentheses_match(input):
s = []
balanced = True
index = 0
while index < len(input) and balanced:
token = input[index]
if token == "(":
s.append(token)
elif token == ")":
if len(s) == 0:
balanced = False
else:
s.pop()

index += 1

return balanced and len(s) == 0