0

Balanced paranthesis

I have problem in this code ... Anyone plz help me with this code In this code, 7testcases ,5succed... def balanced(expression): #your code goes here list=[] for i in expression : if i=='(' : list.insert(0,i) l=len(list) c=0 for i in expression : if i==')': list.pop(0) c+=1 a=expression.index('(') b=expression.index(')') if l==c and a<b and list==[]: return 'True' else: return 'False' print(balanced(input()))

26th Feb 2021, 2:57 AM
Saran M
Saran M - avatar
3 ответов
+ 4
I guess you should try to think of another simplest way, as you seems confuse... very first part if your logic is almost rigtht, but last parts? you should iterate over input string, and test at once for '(' and ')'... you could also use a counter rather than a list, but with a list, instead of insert use append method (converse of pop). ;) try it again, and if you're still stuck, let me know else mark my answer as best and upvote :)
26th Feb 2021, 3:15 AM
visph
visph - avatar
+ 2
You need an error handling for case when the code tries to remove the element from an empty list. Tip: try to use comparing with empty list or "try/except" statement.
26th Feb 2021, 4:49 AM
#0009e7 [get]
#0009e7 [get] - avatar
+ 1
If you want to solve 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)
28th Feb 2021, 12:19 PM
Uzair Karjikar
Uzair Karjikar - avatar