Posted By

AlexanderRavikovich on 11/01/12


Tagged

math parentheses


Versions (?)

Math expression syntax validator of parentheses in Python 3


 / Published in: Python
 

Soma example of validation parentheses in math expressions.

[{()}] - valid [{){}] - wrong

  1. # Mathematical expression to validate
  2. code = "[(((a+b)*c+d-e)/(f+g)-(r+j)*(k+e))]";
  3.  
  4. parentheses_open = ['(', '{', '[']
  5. parentheses_close = [')', '}', ']']
  6.  
  7. def getParenthesesType(c):
  8. if c in parentheses_open:
  9. return parentheses_open.index(c)
  10. elif c in parentheses_close:
  11. return parentheses_close.index(c)
  12. else:
  13. return 0
  14.  
  15. def validateSyntax(x):
  16. size = len(x)
  17. s = []
  18. for i in range(0, size):
  19. if x[i] in parentheses_open:
  20. s.append(x[i])
  21. elif x[i] in parentheses_close:
  22. if len(s)==0:
  23. return 0
  24. if getParenthesesType(s.pop()) != getParenthesesType(x[i]):
  25. return 0
  26. if len(s)==0:
  27. return 1
  28. else:
  29. return 0
  30.  
  31. if validateSyntax(code):
  32. print("Valid")
  33. else:
  34. print("Wrong")

Report this snippet  

You need to login to post a comment.