Balanced Parentheses | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Balanced Parentheses

NEED HELP WITH THIS 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 " My program does the job, but all the "test cases" doesn't go green. Here is my code: class Stack: def __init__(self): self.items = [] def push(self, item): self.items.insert(0,item) def pop(self): return self.items.pop(0) def print_stack(self): if not self.items: print("True") else: print("False") n = input() s = Stack() for i in n: if i == '(': s.push('(') elif i == ')': s.pop() s.print_stack()

16th Aug 2021, 7:03 AM
mariusep
2 Answers
+ 3
Your code throws exception when you s.pop and self.items is empty. When that happens it means there are more ')' than '(' at that point.
16th Aug 2021, 8:05 AM
你知道規則,我也是
你知道規則,我也是 - avatar
+ 1
Program does the job, only with balanced parentheses. Why didn't you yourself test the example "7- (3 (2 * 9)) 4) (1"? 🤔 In this case, s.pop() tries to from the empty stack, which leads to an error. The solution to this problem is very simple, you only need to remove two characters from your code. ☺️
16th Aug 2021, 8:18 AM
Solo
Solo - avatar