0
[solved] Balanced parenthesis python
Hi. I’m trying to solve the balanced parenthesis project, but sometimes cases 1 and 4 aren’t solved, and sometimes case 7 isn’t solved. Can anybody please help me? 🙏
3 Respuestas
+ 1
Hey ravilnicki! That was the problem: the return len(x) == 0 was inside the for. Thank you so much!!!
0
#Cases 1 and 4 don’t work
def balanced(expression):
#your code goes here
x = []
for i in expression:
if i == "(":
x.insert(0, i)
elif i == ")":
if len(x) > 0:
x.pop(0)
else:
return False
return len(x) == 0
print(balanced(input()))
#Case 7 doesn’t work
def balanced(expression):
#your code goes here
open = 0
close = 0
for i in expression:
if i == "(":
open += 1
elif i == ")":
close += 1
if open != close:
return False
else:
return open == close
print(balanced(input()))