This repo contains code to mirror other repos. It also contains the code that is getting mirrored.
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

61 lignes
1.2 KiB

  1. from lark.tree import InlineTransformer
  2. from lark.lark import Lark
  3. calc_grammar = """
  4. ?start: sum
  5. | NAME "=" sum -> assign_var
  6. ?sum: product
  7. | sum "+" product -> add
  8. | sum "-" product -> sub
  9. ?product: atom
  10. | product "*" atom -> mul
  11. | product "/" atom -> div
  12. ?atom: /[\d.]+/ -> number
  13. | "-" atom -> neg
  14. | NAME -> var
  15. | "(" sum ")"
  16. NAME: /\w+/
  17. WS.ignore: /\s+/
  18. """
  19. class CalculateTree(InlineTransformer):
  20. from operator import add, sub, mul, div, neg
  21. number = float
  22. def __init__(self):
  23. self.vars = {}
  24. def assign_var(self, name, value):
  25. self.vars[name] = value
  26. return value
  27. def var(self, name):
  28. return self.vars[name]
  29. calc_parser = Lark(calc_grammar, parser='lalr', transformer=CalculateTree())
  30. calc = calc_parser.parse
  31. def main():
  32. while True:
  33. try:
  34. s = raw_input('> ')
  35. except EOFError:
  36. break
  37. print(calc(s))
  38. def test():
  39. # print calc("a=(1+2)")
  40. print calc("a = 1+2")
  41. print calc("1+a*-3")
  42. if __name__ == '__main__':
  43. test()
  44. # main()