+ 5

HELP 28 Code Project Balanced Parentheses (Python Data Structures)

Can someone help me figure what's wrong with my code? Two of the test cases are not working, but they are hidden so I don't know what's wrong. "Balanced Parentheses Parentheses are balanced, if all opening parentheses have their corresponding closing parentheses. Given an expression as input, we need to find out whether the parentheses are balanced or not. For example, "(x+y)*(z-2*(6))" is balanced, while "7-(3(2*9))4) (1" is not balanced. The problem can be solved using a stack. Push each opening parenthesis to the stack and pop the last inserted opening parenthesis whenever a closing parenthesis is encountered. If the closing bracket does not correspond to the opening bracket, then stop and say that the brackets are not balanced. Also, after checking all the parentheses, we need to check the stack to be empty -- if it's not empty, then the parentheses are not balanced. Implement the balanced() function to return True if the parentheses in the given expression are balanced, and False if not. Sample Input: (a( ) eee) ) Sample Output: False" My code: exp = input() def balanced(expression): list = [] for item in exp: if item == "(": list.insert(0, item) for item in exp: if item == ")": list.pop(0) if list == []: return True else: return False print(balanced(exp)) Thank you!

14th Oct 2021, 7:16 PM
Debora Reichert
Debora Reichert - avatar
5 ответов
+ 3
Oh no, that's true :( Then I don't even know where to start. Thank you
14th Oct 2021, 8:16 PM
Debora Reichert
Debora Reichert - avatar
0
If input is ")(" then your code return ture for this . But need false. Hope it helps..
14th Oct 2021, 8:04 PM
Jayakrishna 🇮🇳
0
Hint: if ")" comes before "(" to list then it's unbalanced.. consider list size in pop(). hope it helps... You're welcome...
14th Oct 2021, 8:24 PM
Jayakrishna 🇮🇳
0
1. You can use a single for loop and if and elif. 2. If item is a closing parenthesis first check if the length of list is greater than zero. If it is use pop, if it isn't return False.
14th Oct 2021, 10:31 PM
Simon Sauter
Simon Sauter - avatar
- 1
for i in x: if i == "(": list.insert(0, i) elif i == ")" and list != []: list.pop() elif i == ")" and list == []: list.insert(0, i)
6th May 2022, 8:30 PM
Mustafa Al-jawdah
Mustafa Al-jawdah - avatar