I need assistance here, please. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

I need assistance here, please.

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 https://code.sololearn.com/crdP8KlKuOso/?ref=app

16th Feb 2022, 11:10 AM
Frimpong Godfred
Frimpong Godfred - avatar
5 Answers
+ 1
Yes. You can check list is not empty before pop. Or in other way, if you know about, try ctach, on empty list, pop opearation raise error. So try catch will help to return false. But the first thing easy if len(list) == 0 : return false else : list.pop()
16th Feb 2022, 11:48 AM
Jayakrishna 🇮🇳
+ 2
Frimpong Godfred You could first check if the list is empty (before pop). If it not should you can already return false.
16th Feb 2022, 11:40 AM
JaScript
JaScript - avatar
+ 1
These two have not work in any way.. if '(' or ')' is i: it is always true. May you trying is if i in ( '(', ')' ) : Or if i=='(' or i== ')' : return len(list) == None, always return false since input have at least a charecter and it is added to list. You never tried to pop elements.. Also len() never returns None. it rerun a number (0 or length) Try this way: ** take input ** if input's charecter '(' , add to list ** if input's charecter is ')' pop from list. If not successful return false ** if list is empty, return true else return false... Hope it helps...
16th Feb 2022, 11:27 AM
Jayakrishna 🇮🇳
+ 1
Jayakrishna🇮🇳 I don't get it. If it's '(' , I add it to the list. Bur when it's ')' , how can I pop it out of the list when I've not added it to the list yet.
16th Feb 2022, 11:35 AM
Frimpong Godfred
Frimpong Godfred - avatar
16th Feb 2022, 5:08 PM
Frimpong Godfred
Frimpong Godfred - avatar