This repo contains code to mirror other repos. It also contains the code that is getting mirrored.
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 

64 řádky
1.2 KiB

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