您的位置:首页 > 编程语言 > Python开发

用50行Python代码制作一个计算器

2015-11-04 16:36 756 查看
简介在这篇文章中,我将向大家演示怎样向一个通用计算器一样解析并计算一个四则运算表达式。当我们结束的时候,我们将得到一个可以处理诸如 1+2*-(-3+2)/5.6+3样式的表达式的计算器了。当然,你也可以将它拓展的更为强大。 不废话,直接上代码:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#_auth by kk

# calc.py - # A simple calculator without using eval

import operator as op
from plyplus import Grammar, STransformer

calc_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_operator

def 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()


注意,因为一开始是木有plyplus模块,所以小伙伴们记得用pip install plyplus来进行安装,最后的效果如图[root@django opt]# python cacl.py
> 1+2*-(-3+2)/5.6+3
4.35714285714
>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息