0

Python balanced Parenthesis help

I can't find out why it doesn't make the length of expression into 0 to print True for ssome test cases, anyone know what's missing? def balanced(expression): expression = list(expression.split()) try: for i in expression: if i == '(': expression.insert(0, i) elif i == ')': expression.pop(0, i) finally: if len(expression) == 0: return True elif len(expression) > 0: return False print(balanced(input()))

22nd Mar 2021, 11:14 AM
Coalemus
2 Answers
+ 2
expression.split() split the string at white spaces into a list: so list(expression.split()) is redundant... also, roughly you are making a list of words (string), not a list of char... there is very few probabilities to get i==')' or i=='('... try...finally must be used to handle errors... not to... what is your purpose by using them? also, you seems to use the iterated expression as a stack to keep track of parenthesis... you must use another variable dedicated for that and not modify the original expression... hint: to simply iterate over char of expression, don't split and/or list it, just do: for chr in expression: a string is basically a char list, and can be accessed as a char list in almost programming languages ^^
22nd Mar 2021, 11:23 AM
visph
visph - avatar
+ 1
Thank you!
22nd Mar 2021, 11:26 AM
Coalemus