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.

69 lignes
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: /[\d.]+/ -> number
  19. | "-" atom -> neg
  20. | NAME -> var
  21. | "(" sum ")"
  22. NAME: /[a-zA-Z]\w*/
  23. WS.ignore: /\s+/
  24. """
  25. class CalculateTree(InlineTransformer):
  26. from operator import add, sub, mul, truediv as div, neg
  27. number = float
  28. def __init__(self):
  29. self.vars = {}
  30. def assign_var(self, name, value):
  31. self.vars[name] = value
  32. return value
  33. def var(self, name):
  34. return self.vars[name]
  35. calc_parser = Lark(calc_grammar, parser='lalr', transformer=CalculateTree())
  36. calc = calc_parser.parse
  37. def main():
  38. while True:
  39. try:
  40. s = input('> ')
  41. except EOFError:
  42. break
  43. print(calc(s))
  44. def test():
  45. print(calc("a = 1+2"))
  46. print(calc("1+a*-3"))
  47. if __name__ == '__main__':
  48. # test()
  49. main()