+ 1

any answer plz ?

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

20th Jul 2021, 10:38 AM
Mostafa Alafif
Mostafa Alafif - avatar
2 Respostas
+ 2
How can we answer, when you have not asked a question. This is a code challenge. Please attach your attempt with a query outlining your difficulty.
20th Jul 2021, 10:45 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 2
If you have an opening parentheses, then you need to have a closing one as well. If you don't, it's unbalanced. If you do, it's balanced. If that's still confusing, add up all opening/closing parentheses and see if it's even or odd; even = balanced, odd = unbalanced. As for the coding part, this is why word problems were important in math class. They told you exactly what to code, you just need to convert it from words to programming language. Read the problem again and then do it line by line. It wants you to push/pop into a stack, compare opening against closing parentheses and ensure the stack is empty. All means and conditions to figure out if it's balanced or not.
20th Jul 2021, 3:05 PM
Jakko Jak
Jakko Jak - avatar