Please i need help with this exercise, can anyone please explain how can i do it, i will really appreciate | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Please i need help with this exercise, can anyone please explain how can i do it, i will really appreciate

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

7th Jan 2023, 11:42 AM
Bello Muktar
Bello Muktar - avatar
2 Answers
+ 1
If stack is not a requirement, you can simply count left parentheses and right parentheses and check if they are equal ->> it's balanced, if not ->> it's not balanced. https://www.w3schools.com/JUMP_LINK__&&__python__&&__JUMP_LINK/ref_list_count.asp Otherwise Stack and Queue are easy to understand, just practice more with basic examples. https://stackabuse.com/stacks-and-queues-in-python/
7th Jan 2023, 12:49 PM
iTech
iTech - avatar
+ 1
Thank you very much for the useful information.
7th Jan 2023, 12:56 PM
Bello Muktar
Bello Muktar - avatar