- 1

Python data structure balanced paranthesess project last test incorrect but why. Help

def balanced(n): a = n.count(")") b = n.count("(") if a == b: print("True") else: print("False") balanced(input()) Why getting last test case incorrect

7th Mar 2021, 2:24 PM
S UZAIR ASIF
S UZAIR ASIF - avatar
4 Réponses
0
So solve how this.thank. lista = list() Def balanced(expression): item = list(expression) For i in item: if i == ' ( ' : lista.insert(0,i) elif i == ' ) ' : if lista == [] : return False else: lista.pop(0) if lista == []: return True else: return False Print(balanced(input())) Return True Else: Return False
30th Jul 2021, 1:18 AM
Mario Gomez
Mario Gomez - avatar
+ 5
the task description for balanced parentheses says: ▪︎You can use a simple list for a stack. Use list.insert(0, item) to push on the stack, and list.pop(0) to pop the top item. You can access the top element of the stack using list[0]. doing like this, you should solve the issue. happy coding!
7th Mar 2021, 4:04 PM
Lothar
Lothar - avatar
+ 1
The program isn't that simple ,your code doesn't checks for something like this "() ()) (", ? if you can't figure out how to find for something like above i will add a code i think might work, so let me know.
7th Mar 2021, 3:04 PM
Abhay
Abhay - avatar
+ 1
The task is to solve it with stack:- 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)
7th Mar 2021, 4:51 PM
Uzair Karjikar
Uzair Karjikar - avatar