Use 50 lines of Python code to create a calculator
In this article, I will show you how to parse and calculate a four-digit arithmetic expression just like a common calculator. When we end, we will get a calculator that can process expressions such as 1 + 2 *-(-3 + 2)/5.6 + 3. Of course, you can also expand it more powerful. No nonsense. directly add the Code:
#!/usr/bin/env python# -*- coding: utf-8 -*-#_auth by kk# calc.py - # A simple calculator without using evalimport operator as opfrom plyplus import Grammar, STransformercalc_grammar = Grammar(""" start: add; ?add: (add add_symbol)? mul; ?mul: (mul mul_symbol)? atom; @atom: neg | number | '\(' add '\)'; neg: '-' atom; number: '[\d.]+'; mul_symbol: '\*' | '/'; add_symbol: '\+' | '-'; WS: '[ \t]+' (%ignore);""")class Calc(STransformer): def _bin_operator(self, exp): arg1, operator_symbol, arg2 = exp.tail operator_func = { '+': op.add, '-': op.sub, '*': op.mul, '/': op.div }[operator_symbol] return operator_func(arg1, arg2) number = lambda self, exp: float(exp.tail[0]) neg = lambda self, exp: -exp.tail[0] __default__ = lambda self, exp: exp.tail[0] add = _bin_operator mul = _bin_operatordef main(): calc = Calc() while True: try: s = raw_input('> ') except EOFError: break if s == '': break tree = calc_grammar.parse(s) print(calc.transform(tree))main()
Note: Since the plyplus module is available in the beginning, you may remember to use pip install plyplus for installation. The final effect is [root @ django opt] # python cacl. py> 1 + 2 *-(-3 + 2)/5.6 + 34.35714285714>