+ 1

The last project on the python data structures course ( balanced parentheses )

My code passed all test cases except for the last one (test case #7). What can I do to make it pass that case? My code has to output True if the parentheses are balanced and False otherwise. For example, "(1+2)×(-2)" is balanced, while "(12)×7)" is not balanced. My code: def balanced(expression): #your code goes here par = [] for i in expression: if i == "(": par.insert(0, i) for i in expression: if i == ")": if len(par) != 0: par.pop() else: return False if len(par) != 0: return False else: return True print(balanced(input()))

4th Jan 2024, 5:19 AM
Kamela Yunisa
3 Réponses
+ 3
As task description mentioned "7-(3(2*9))4) (1" is not balanced, although it has the same number of "(" and ")".
5th Jan 2024, 1:48 AM
Wong Hei Ming
Wong Hei Ming - avatar
+ 2
Wong Hei Ming ah... I understand... my code can't handle the case when ")" comes before "(", thank you! I'll try to debug it
5th Jan 2024, 2:32 AM
Kamela Yunisa
+ 1
Without seeing your code, there is no point in guessing what you might be doing wrong. Maybe you forgot about an "edge case", a special scenario or strange kind of input. If you explain the task, and link your code, maybe someone can review and find the error in your logic.
4th Jan 2024, 6:59 AM
Tibor Santa
Tibor Santa - avatar