fork download
  1. from collections import deque
  2.  
  3. def check(val1,val2):
  4. return (val1=="(" and val2==")") or (val1=="{" and val2=="}") or (val1=="[" and val2=="]")
  5.  
  6. def exp_stack(exp):
  7. stack=deque()
  8. for i in range(len(exp)):
  9. if (exp[i]=="(" or exp[i]=="{" or exp[i]=="["):
  10. stack.append(exp[i])
  11. else:
  12. if len(stack)==0:
  13. return False
  14. elif check(stack[-1],exp[i]):
  15. stack.pop()
  16. continue
  17. return False
  18. return True
  19.  
  20. exp = "({})[]"
  21.  
  22. if exp_stack(exp):
  23. print("Balanced")
  24. else:
  25. print("Not Balanced")
Success #stdin #stdout 0.04s 9704KB
stdin
45
stdout
Balanced