- 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()))

20th May 2021, 10:34 PM
Suleman Abdul Manan
Suleman Abdul Manan - avatar
2 Réponses
+ 2
Line 8 throws an error if list is empty
20th May 2021, 10:54 PM
Benjamin Jürgens
Benjamin Jürgens - avatar
+ 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()))
21st May 2021, 4:07 AM
A͢J
A͢J - avatar