+ 2
Balanced parenthesis
Why it is wrong?This code is failing in test 3... code is: def balanced(expression): list=[] for item in expression: if item=="(" or item==")": if item=="(": list.insert(0,item) if "("in list and item==")": list.pop(0) if list==[]: return True else: return False print(balanced(input()))
6 Antworten
+ 5
Hadise, the following is a bit simpler and based on the observation that the stack of only "(" characters is nothing but a glorified counter.
def balanced(expression):
count = 0
for char in expression:
if char == "(":
count += 1
elif char == ")":
if count == 0:
return False
count -= 1
return count == 0
print(balanced(input()))
+ 5
Well, I wrote this code and it was correct😉
def balanced(expression):
x=[]
for letter in expression:
if letter == "(":
x.insert(0,letter)
if letter ==")":
if x != []:
x.pop(0)
elif x==[]:
return False
if x==[]:
return True
else:
return False
print(balanced(input()))
+ 2
)
That isn't balanced but your code will incorrectly say it is.
I don't know what test case 3 is but you should fix the above problem and see if your tests pass.
+ 2
Oop, I must have accidentally deleted my post, but ya pretty much same as what Josh Greig said anyway.
+ 2
Good job Josh Greig😀
Yeah, Your code is simpler than mine.😁
Thanks for your good suggestion.💫
+ 1
Have you considered what will happen if there are more ")"s than "("s?