- 1
Help find bugs in this code
def balanced(expression): #your code goes here list=[] for i in expression: if (i=="("): list.insert(0,"(") elif (i==")" ): if (list[0]=="("): list.pop(0) else: return False else: continue if (len(list)==0): return True else: return False print(balanced(input()))
2 odpowiedzi
+ 2
Line 8 throws an error if list is empty
+ 2
Suleman Abdul Manan
Here is a complete solution of your problem. I have added two case here:
1 - what if expression has ")" and your list is not empty
2 - what if expression has only ")" and your list is empty (in this case list[0] will give error)
So I have checked these two cases.
-------------------
def balanced(expression):
#your code goes here
list = []
for i in expression:
if i == "(":
list.insert(0, "(")
elif i == ")" and len(list) != 0:
if list[0] == "(":
list.pop(0)
else:
return False
elif i == ")" and len(list) == 0:
return False
if (len(list) == 0):
return True
else:
return False
print(balanced(input()))