Balanced Parenthesis // python data-structures | Sololearn: Learn to code for FREE!

+1

Balanced Parenthesis // python data-structures

def balanced(l): s=[] for i in l: if i == "(": s.insert(0,i) elif i ==")": if s==[] : return False s.pop(0) return s==[] print(balanced(input())) ---------------------------------------- def balanced(l): if l.find('(') > l.find(')') : return False s = [] for i in l : if i == '(' : s.insert(0, i) elif i == ')' : s.pop(0) return s==[] print(balanced(input())) Why this two codes are not gave same results for test case #7 ???

7/18/2021 11:20:28 AM

Pranav Hirani

1 Answer

New Answer

+7

Hirani Pranav , the second code crashes if input is e.g.: (()(())))) ▪︎the first code checks for an empty list with: if s==[] : return False ▪︎the second code is not doing this check and ends up with an exception: < IndexError: pop from empty list >