This repo contains code to mirror other repos. It also contains the code that is getting mirrored.
Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

60 Zeilen
1.2 KiB

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