2017-02-14 11:12:00 +00:00
|
|
|
#
|
|
|
|
# This example shows how to write a basic calculator with variables.
|
|
|
|
#
|
|
|
|
|
2018-05-18 12:14:57 +00:00
|
|
|
from lark import Lark, Transformer, visitor_args
|
2017-02-05 11:40:19 +00:00
|
|
|
|
2017-02-15 08:00:01 +00:00
|
|
|
try:
|
2017-08-04 13:05:40 +00:00
|
|
|
input = raw_input # For Python2 compatibility
|
2017-02-15 08:00:01 +00:00
|
|
|
except NameError:
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
2017-02-05 11:40:19 +00:00
|
|
|
calc_grammar = """
|
|
|
|
?start: sum
|
|
|
|
| NAME "=" sum -> assign_var
|
|
|
|
|
|
|
|
?sum: product
|
|
|
|
| sum "+" product -> add
|
|
|
|
| sum "-" product -> sub
|
|
|
|
|
|
|
|
?product: atom
|
|
|
|
| product "*" atom -> mul
|
|
|
|
| product "/" atom -> div
|
|
|
|
|
2017-02-25 16:35:31 +00:00
|
|
|
?atom: NUMBER -> number
|
2017-02-05 11:40:19 +00:00
|
|
|
| "-" atom -> neg
|
|
|
|
| NAME -> var
|
|
|
|
| "(" sum ")"
|
|
|
|
|
2017-02-23 17:08:23 +00:00
|
|
|
%import common.CNAME -> NAME
|
2017-02-25 16:35:31 +00:00
|
|
|
%import common.NUMBER
|
2017-02-23 17:08:23 +00:00
|
|
|
%import common.WS_INLINE
|
2017-02-23 11:00:16 +00:00
|
|
|
|
2017-02-23 17:08:23 +00:00
|
|
|
%ignore WS_INLINE
|
2017-02-05 11:40:19 +00:00
|
|
|
"""
|
|
|
|
|
2018-05-18 12:14:57 +00:00
|
|
|
@visitor_args(inline=True)
|
|
|
|
class CalculateTree(Transformer):
|
2017-02-12 16:37:43 +00:00
|
|
|
from operator import add, sub, mul, truediv as div, neg
|
2017-02-05 11:40:19 +00:00
|
|
|
number = float
|
|
|
|
|
|
|
|
def __init__(self):
|
|
|
|
self.vars = {}
|
|
|
|
|
|
|
|
def assign_var(self, name, value):
|
|
|
|
self.vars[name] = value
|
|
|
|
return value
|
|
|
|
|
|
|
|
def var(self, name):
|
|
|
|
return self.vars[name]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
calc_parser = Lark(calc_grammar, parser='lalr', transformer=CalculateTree())
|
|
|
|
calc = calc_parser.parse
|
|
|
|
|
|
|
|
def main():
|
|
|
|
while True:
|
|
|
|
try:
|
2017-02-15 08:00:01 +00:00
|
|
|
s = input('> ')
|
2017-02-05 11:40:19 +00:00
|
|
|
except EOFError:
|
|
|
|
break
|
|
|
|
print(calc(s))
|
|
|
|
|
|
|
|
def test():
|
2017-02-12 16:37:43 +00:00
|
|
|
print(calc("a = 1+2"))
|
|
|
|
print(calc("1+a*-3"))
|
2017-02-05 11:40:19 +00:00
|
|
|
|
|
|
|
if __name__ == '__main__':
|
2017-02-15 08:00:01 +00:00
|
|
|
# test()
|
|
|
|
main()
|
2017-02-05 11:40:19 +00:00
|
|
|
|