In: Computer Science
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(<bcd>ef)g abcde a(b)c<<d>e(fg)>
and here are a few examples where the brackets are not balanced:
ab(cde> a<bc>)def<g> 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 therefore likely that your function definition will begin as follows:
def balanced_brackets(text): s = Stack() ...
For example:
Test | Result |
---|---|
print(balanced_brackets('(<x>)(())()')) |
True |
print(balanced_brackets('x(y)z')) |
True |
Thanks for the question. Below is the code you will be needing Let me know if you have any doubts or if you need anything to change. Thank You !! =========================================================================== def balanced_brackets(text): s = Stack() for letter in text: if letter in ['(', '<']: s.push(letter) if letter in [')', '>']: if s.is_empty(): return False top_letter = s.pop() if (letter == ')' and top_letter == '(') or (letter == '>' and top_letter == '<'): continue else: return False if not s.is_empty(): return False return True print(balanced_brackets('(<x>)(())()')) print(balanced_brackets('x(y)z'))