Balanced Parenthesis // python data-structures | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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 ???

18th Jul 2021, 11:20 AM
Pranav Hirani
Pranav Hirani - avatar
1 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 >
18th Jul 2021, 12:53 PM
Lothar
Lothar - avatar