This repo contains code to mirror other repos. It also contains the code that is getting mirrored.
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

72 wiersze
1.3 KiB

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