+ 1

How to complete python course 4th project? (Python, Data Structures)

def balanced(expression): #your code goes here list=[] for i in expression : if i=="(": list.insert(0,i) elif i==")": list.pop(0) if list==[]: return True else: return False print(balanced(input())) https://code.sololearn.com/cEV3TnRxdBbl/?ref=app

6th Nov 2021, 2:19 PM
Parth Chauhan
Parth Chauhan - avatar
6 Answers
0
You can use a list for that. If ( in expression, insert it at 0, if ) in expression, remove last element If the list is empty at the end, return True, else return False. Make sure to catch cases of empty lists
7th Nov 2021, 10:31 AM
Lisa
Lisa - avatar
0
Try to avoid giving variables the same name as built-in functions have. Consider the case of empty lists before trying to remove an element
7th Nov 2021, 11:17 AM
Lisa
Lisa - avatar
0
I tested your code. It gives error for example for the inputs ) or )(
7th Nov 2021, 5:30 PM
Lisa
Lisa - avatar
0
Yes i got your point
8th Nov 2021, 7:06 AM
Parth Chauhan
Parth Chauhan - avatar
0
Thank you Rafal
8th Nov 2021, 12:45 PM
Parth Chauhan
Parth Chauhan - avatar
0
def balanced(expression): list = [] abre = 0 fecha = 0 for i in expression : if i == '(': abre += 1 if i == ')' : fecha += 1 if abre >= fecha: for i in expression : if i == '(': list.insert(0,1) if i == ')' : if list != []: list.pop(0) if abre < fecha: for i in expression : if i == ')': list.insert(0,1) if i == '(' : if list != []: list.pop(0) if list ==[] : return True else: return False print(balanced(input()))
13th Jan 2023, 3:37 PM
Gabriela Reghelin
Gabriela Reghelin - avatar