Question

need help with balancing brackets in python. I don't really understand it much. For this exercise, you must write a function called balanced brackets brackets in the string, that is: ( , ) and >, are c

an unbalanced one will look like this: (<x)>(())()

0 0
Add a comment Improve this question Transcribed image text
Answer #1

'''

Python version : 3.6

Python program to create a function balanced_brackets that returns

if the brackets in a given expression are balanced or not

'''

def balanced_brackets(text):       

               s = Stack() # create s an object of Stack

               # loop over the characters in text

               for ch in text:

                             

                              if ch == '(' or ch == '<':

                                             s.push(ch) # assuming Stack has a method push that inserts an element on top of stack

                              elif ch == ')': # if ch = )

                                             # check if stack is empty or the top element of stack != ( the return false

                                             # assuming Stack has a method isEmpty that returns True of stack is empty

                                             # assuming Stack has a method pop() that removes and returns the top element of the stack

                                             if(s.isEmpty() or s.pop() != '('):

                                                            return False

                              elif ch == '>': # if ch = >

                                             # check if stack is empty or the top element of stack != < the return false

                                             # assuming Stack has a method isEmpty that returns True of stack is empty

                                             # assuming Stack has a method pop() that removes and returns the top element of the stack

                                             if(s.isEmpty() or s.pop() != '<'):

                                                            return False

              

               # if stack is not empty, return False

               if not s.isEmpty():

                              return False

                             

               return True # brackets are balanced

#end of program

Code Screenshot:

Python version: 3.6 Python program to create a function balanced brackets that returns if the brackets in a given express

Add a comment
Know the answer?
Add Answer to:
need help with balancing brackets in python. I don't really understand it much. an unbalanced one...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • [3] In python, please help me write the functions needed for this problem: Another Way to do Parentheses: For this probl...

    [3] In python, please help me write the functions needed for this problem: Another Way to do Parentheses: For this problem, you will be given a string that contains parentheses, brackets, and curly braces ( (, ), [, ], {,} ) and other characters. As a human you are given a string of any characters, determine if the parentheses, brackets, and braces match. (No trailing or leading parentheses). The function called on an empty string will return True. Parentheses must...

  • PYTHON. Continues off another code. I don't understand this. Someone please help! Comment the lines please...

    PYTHON. Continues off another code. I don't understand this. Someone please help! Comment the lines please so I can understand LinkedList ADT: class myLinkedList:     def __init__(self):         self.__head = None         self.__tail = None         self.__size = 0     def insert(self, i, data):         if self.isEmpty():             self.__head = listNode(data)             self.__tail = self.__head         elif i <= 0:             self.__head = listNode(data, self.__head)         elif i >= self.__size:             self.__tail.setNext(listNode(data))             self.__tail = self.__tail.getNext()         else:             current = self.__getIthNode(i - 1)             current.setNext(listNode(data,...

  • PYTHON. Continues off another code(other code is below). I don't understand this. Someone please help! Comment...

    PYTHON. Continues off another code(other code is below). I don't understand this. Someone please help! Comment the lines please so I can understand. There are short and med files lengths for each the list of names/ids and then search id file. These are the input files: https://codeshare.io/aVQd46 https://codeshare.io/5M3XnR https://codeshare.io/2W684E https://codeshare.io/5RJwZ4 LinkedList ADT to store student records(code is below). Using LinkedList ADT instead of the Python List. You will need to use the Student ADT(code is below) Imports the Student class...

  • **TStack.py below** # CMPT 145: Linear ADTs # Defines the Stack ADT # # A stack (also called a pushdown or LIFO stack)...

    **TStack.py below** # CMPT 145: Linear ADTs # Defines the Stack ADT # # A stack (also called a pushdown or LIFO stack) is a compound # data structure in which the data values are ordered according # to the LIFO (last-in first-out) protocol. # # Implementation: # This implementation was designed to point out when ADT operations are # used incorrectly. def create(): """ Purpose creates an empty stack Return an empty stack """ return '__Stack__',list() def is_empty(stack): """...

  • 12p I need help this is Python EXCEPTIONS: It's easier to ask forgiveness than permission. Try...

    12p I need help this is Python EXCEPTIONS: It's easier to ask forgiveness than permission. Try the code and catch the errors. The other paradigm is 'Look before you leap' which means test conditions to avoid errors. This can cause race conditions. 1.Write the output of the code here: class MyError(Exception): pass def notZero(num): if num == 0: raise MyError def run(f): try: exec(f) except TypeError: print("Wrong type, Programmer error") except ValueError: print("We value only integers.") except Zero Division Error:...

  • Python REALLY NEED HELP !!!!!!!!! [10pts] Write the class Vector that supports the basic vector operations....

    Python REALLY NEED HELP !!!!!!!!! [10pts] Write the class Vector that supports the basic vector operations. Such operations are addition (+) and subtraction (-) of vectors of the same length, dot product (*) and multiplication (*) of a vector by a scalar. All methods must return (not print) the result. Your class should also support the rich comparison for equality (==) - You must use the special methods for those 4 operators in order to override their behavior - You...

  • Hi, I need some help finishing the last part of this Python 1 code. The last...

    Hi, I need some help finishing the last part of this Python 1 code. The last few functions are incomplete. Thank you. The instructions were: The program has three functions in it. I’ve written all of break_into_list_of_words()--DO NOT CHANGE THIS ONE. All it does is break the very long poem into a list of individual words. Some of what it's doing will not make much sense to you until we get to the strings chapter, and that's fine--that's part of...

  • Greeting! Kindly help me to solve my finals in PYTHON, I don't have a knowledge in...

    Greeting! Kindly help me to solve my finals in PYTHON, I don't have a knowledge in PYTHON, new student. Please, please, I'm begging, Kindly answers all the questions. I'm hoping to grant my request. Thanks in advanced. 1.) What is the output of the following snippet? l1 = [1,2] for v in range(2): l1.insert(-1,l1[v]) print(l1)        a.) [1, 2, 2, 2]        b.) [1, 1, 1, 2]        c.) [1, 2, 1, 2]        d.) [1,...

  • I really need help with this python programming assignment Program Requirements For part 2, i need...

    I really need help with this python programming assignment Program Requirements For part 2, i need the following functions • get floats(): It take a single integer argument and returns a list of floats. where it was something like this def get_floats(n):   lst = []   for i in range(1,n+1):     val = float(input('Enter float '+str(i)+': '))     lst.append(val)   return lst • summer(): This non-void function takes a single list argument, and returns the sum of the list. However, it does not use...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT