0

i cannot find answer for this problem plz anyone hlp me to solve this prblm.

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

5th Jun 2021, 6:39 AM
swetha R
5 ответов
+ 1
class Stack: def __init__(self): self.items = [] def push(self, item): self.items.insert(0, item) def pop(self): return self.items.pop(0) s = Stack() inp = input() def balanced(inp): try: for i in inp: if i == str("("): s.push('(') elif i == str(")"): s.pop() else: continue if len(s.items) == 0: print(" True") else: print("False") except: print("False") balanced(inp) i got answer for my question Thanks for all ur answers.
5th Jun 2021, 12:47 PM
swetha R
0
Ratnapal Shende Your code will work only in case of your given example. If expression is like this (1+2)*2) then what? swetha Explanation is already given in the lesson. Use push and pop techniques to solve this problem.
5th Jun 2021, 7:00 AM
A͢J
A͢J - avatar
0
Ratnapal Shende Ok then try your logic in that excercise and tell me what happened.
5th Jun 2021, 7:45 AM
A͢J
A͢J - avatar
0
Ratnapal Shende Is this ) ( balanced?
5th Jun 2021, 7:46 AM
A͢J
A͢J - avatar
0
🅰🅹 🅐🅝🅐🅝🅣 🙆 got it bro! Thank you so much for correction!
5th Jun 2021, 8:03 AM
Ratnapal Shende
Ratnapal Shende - avatar