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.
 
 

83 líneas
1.6 KiB

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