+ 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
7 Réponses
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
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
0
I tested your code. It gives error for example for the inputs
)
or
)(
0
Yes i got your point
0
Thank you Rafal
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()))