0
Someone can help in Balanced Parentheses im stuck:( this is my code
def balanced(expression): x = expression lst = [] parentheses_count = 0 for i in x: if i == '(': lst.append(i) parentheses_count += 1 elif i == ')': lst.append(i) parentheses_count -= 1 if parentheses_count == 0: return True elif parentheses_count < 0: return False else: return False print(balanced(input()))
3 Respuestas
+ 1
When i is a closing parenthesis ')' I think you should do lst.pop(-1) instead of lst.append(i).
You will have to check for errors. Consider what happens with the pop in case the parentheses are out of order, such as '))('. In that case you would return false right away.
+ 1
Brian I'm still stuck it's very hard xd
+ 1
You can do it without keeping track of parentheses_count. Use the list as a stack, and check in strategic places whether the list is empty. In some places it should not be empty.
if lst==[]: break
At the end It should be empty.
if lst==[]:
return true
return false