0

I need help

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

15th Jul 2022, 7:06 AM
Siyabonga Mosibi
Siyabonga Mosibi - avatar
4 ответов
+ 3
Please link your attempt from Sololearn Playground with a question about problems first. Then you can expect a help.
15th Jul 2022, 7:14 AM
JaScript
JaScript - avatar
+ 1
Siyabonga Mosibi A concept you could try is to set a variable to 0 IE: balanced = 0 Then iterate through your expression. If the item you are iterating is ( , then balanced +=1. if the item is ) , then balanced -=1. When you have finished iterating through the expression, you could look at the result of balanced. If balanced = 0, then the paranthesis are balanced. Else, the paranthesis are not balanced
15th Jul 2022, 8:15 AM
Rik Wittkopp
Rik Wittkopp - avatar
0
Don't know what the course is, but here is one rudimental method. Create array/list (stack replacement) of parenthesis while parsing text. Check found parenthesis and if those are "(" add them to the array/list. When you get to ")" you delete the last entry from the array/list. If the first parenthesis happens to be ")" and your array/list is empty it's unbalanced. If after going through the whole text your array/list is not empty it's unbalanced. When you got that working try to optimize the code.
15th Jul 2022, 7:37 AM
Alan Gregorić
Alan Gregorić - avatar
0
There is also solution without knowing what Stack is: d = input() l = list(d) b = 0 # any number not equal to 0 x = 5 for i in l: if i == "(": b += 1 elif i == ")": b -= 1 if b < 0: print("False") x = 0 break if b > 0 and x != 0: print("False") elif b == 0 and x != 0: print("True")
17th Nov 2022, 12:58 PM
Dusko Stojanovic
Dusko Stojanovic - avatar