Can not pass internal test | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Can not pass internal test

Hello dear friends! I need a help, I can not pass internal test. Text of task and my code below. Task: 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

4th Jan 2022, 10:01 AM
Lyapunov Alexander
Lyapunov Alexander - avatar
4 Answers
+ 1
Lyapunov Alexander The problem is that you aren't checking the order in which the parentheses are placed. For example, this ain't a valid expression: )78-56(*8())( You'd need a code that checks for the position of the parentheses as well. Check this out: https://code.sololearn.com/c9lz4v3MqcT3/?ref=app
4th Jan 2022, 11:28 AM
Œ ㅤ
Œ ㅤ - avatar
+ 1
Thank you! Your explanation is very detailed and accurate.
4th Jan 2022, 3:49 PM
Lyapunov Alexander
Lyapunov Alexander - avatar
+ 1
4th Jan 2022, 4:42 PM
Œ ㅤ
Œ ㅤ - avatar
0
My code: def balanced(expression): #code list = [] for item in expression: list.insert(0, item) while True: if ("(" in list) and (")" in list): list.remove("(") list.remove(")") else: break #print(list) if "(" in list or ")" in list: return False else: return True print(balanced(input()))
4th Jan 2022, 10:06 AM
Lyapunov Alexander
Lyapunov Alexander - avatar