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

Balanced Parentheses

QUESTION : 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. MY TRY (USING STACK) : def areBracketsBalanced(expr): stack = [] for char in expr: if char in ["("]: stack.append(char) else: if char in ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'x', 'y', 'z', '+', '*', '-']: pass if not stack: return False current_char = stack.pop() if current_char == '(': if char != ")": return False if stack: return False return True if __name__ == "__main__": expr = input() if areBracketsBalanced(expr): print("True") else: print("False") WITHOUT STACK : def balanced(expression): openb = 0 closeb = 0 for i in expression: if i == '(': openb += 1 elif i == ')': closeb += 1 if openb == closeb: return True else: return False print(balanced(input())) i'm unable to get solve all the test cases

31st Oct 2021, 5:12 AM
GURURAJ KL
GURURAJ KL - avatar
3 Answers
+ 8
One problem might be a simple )(. Without stack: Use only one counter and add 1 for "( and substract 1 for ")". Additionally check that counter never becomes less than 0. With stack append "(" if found. Pop "(" if ")" found. Wrap it into try/catch In both cases finally counter and stack must be zero/empty.
31st Oct 2021, 6:48 AM
Oma Falk
Oma Falk - avatar
+ 3
Oma Falk Thank you 😊
31st Oct 2021, 7:11 AM
GURURAJ KL
GURURAJ KL - avatar
+ 2
x =" (1+2)*3+(7*(6+5))*4" def bal(s): opn = s.count("(") cls = s.count(")") if opn == cls: return True else: return False print(bal(x))
31st Oct 2021, 9:41 AM
Shadoff
Shadoff - avatar