This repo contains code to mirror other repos. It also contains the code that is getting mirrored.
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 

76 líneas
1.4 KiB

  1. #
  2. # This example shows how to write a basic calculator with variables.
  3. #
  4. from lark import Lark, Transformer, v_args
  5. try:
  6. input = raw_input # For Python2 compatibility
  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. @v_args(inline=True) # Affects the signatures of the methods
  28. class CalculateTree(Transformer):
  29. from operator import add, sub, mul, truediv as div, neg
  30. number = float
  31. def __init__(self):
  32. self.vars = {}
  33. def assign_var(self, name, value):
  34. self.vars[name] = value
  35. return value
  36. def var(self, name):
  37. return self.vars[name]
  38. calc_parser = Lark(calc_grammar, parser='lalr', transformer=CalculateTree())
  39. calc = calc_parser.parse
  40. def main():
  41. while True:
  42. try:
  43. s = input('> ')
  44. except EOFError:
  45. break
  46. print(calc(s))
  47. def test():
  48. print(calc("a = 1+2"))
  49. print(calc("1+a*-3"))
  50. if __name__ == '__main__':
  51. # test()
  52. main()