I tried this code but I couldn't pass test case 3. Could you please tell me what possibly went wrong? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

I tried this code but I couldn't pass test case 3. Could you please tell me what possibly went wrong?

def balanced(item): items = [] for i in item : if i == '(': items.append(i) elif i ==")" and len(items)>0: items.pop() if (items==[]): return True else: return False print(balanced(input())) #Test case 3 not passed(hidden)

15th Dec 2021, 1:31 PM
Mustafa Yassin Mohammed
Mustafa Yassin Mohammed - avatar
4 Answers
+ 2
You forgot that if you get ")" without any "(" in a stock than it means that it can't balanced no matter what. If you add this check it should pass.
15th Dec 2021, 4:41 PM
Herr Rozwel
Herr Rozwel - avatar
+ 2
When your code encounters a closing parenthesis and items is empty your code does nothing. Instead it should return False and break. So you have to make changes to the elif block.
15th Dec 2021, 6:19 PM
Simon Sauter
Simon Sauter - avatar
+ 1
Herr Rozwel Yes now it works. Thank you for helping.
16th Dec 2021, 9:37 AM
Mustafa Yassin Mohammed
Mustafa Yassin Mohammed - avatar
0
Mustafa Yassin Mohammed I don't know this challenge but I would check what happens when you get an empty String. I guess in this case you should return False but your function returns True.
15th Dec 2021, 4:42 PM
Denise Roßberg
Denise Roßberg - avatar