Advertisement
Guest User

Untitled

a guest
Oct 19th, 2019
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.40 KB | None | 0 0
  1. class Formula:
  2.  
  3. def __init__(self, text):
  4. self.text = text.replace(" ", "")
  5. self.pos = 0
  6.  
  7. def __bool__(self):
  8. return self.pos < len(self.text)
  9.  
  10. def fetch(self):
  11. return self and self.text[self.pos] or " "
  12.  
  13. def pop(self):
  14. self.pos += 1
  15. return self.text[self.pos - 1]
  16.  
  17.  
  18. def calculate(formula):
  19. """
  20. calculate specified formula using BNF.
  21.  
  22. >>> calculate("1-2-3")
  23. -4
  24. >>> calculate("1+2*(3+4)")
  25. 15
  26. """
  27. return expr(Formula(formula))
  28.  
  29.  
  30. def expr(formula):
  31. value = term(formula)
  32. while formula.fetch() in "+-":
  33. op = formula.pop()
  34. if op == "+":
  35. value += term(formula)
  36. elif op == "-":
  37. value -= term(formula)
  38. return value
  39.  
  40.  
  41. def term(formula):
  42. value = factor(formula)
  43. while formula.fetch() in "*/":
  44. op = formula.pop()
  45. if op == "*":
  46. value *= factor(formula)
  47. elif op == "/":
  48. value /= factor(formula)
  49. return value
  50.  
  51.  
  52. def factor(formula):
  53. if formula.fetch() == "(":
  54. formula.pop()
  55. value = expr(formula)
  56. if not formula or formula.pop() != ")":
  57. raise IllegalExpressionException()
  58. else:
  59. value = number(formula)
  60. return value
  61.  
  62.  
  63. def number(formula):
  64. value = ""
  65. while formula.fetch() in "0123456789.":
  66. value += formula.pop()
  67. return ("." in value and float or int)(value)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement