码迷,mamicode.com
首页 > 其他好文 > 详细

Day.9计算器小程序

时间:2017-04-30 14:11:22      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:type   运算   --   orm   赋值   实现   return   元字符   pytho   

开发一个简单的python计算器
1.实现加减乘除及括号优先级解析
2.用户输入 1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )
 等类似公式后,必须自己解析里面的(),+,-,*,/符号和公式(不能调用eval等类似功能偷懒实现),
   运算后得出结果,结果必须与真实的计算器所得出的结果一致

# a=eval(str( 1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )))
# print(a) # 2776672.6952380957  #打死也不能用这个!!!
import re
def calculate(x):
    res=eval(x)
    return res
def myeval():#定义自己的加减乘除,不能用eval!!!(暂没思路,待补全)
    pass
def change(mystr):
    while True:
        if "--" in mystr:
            mystr=re.sub("--","+",mystr)
            continue
        elif "-+" in mystr:
            mystr=re.sub("-\+","-",mystr)
            continue
        elif "++" in mystr:
            mystr=re.sub("\+\+","+",mystr)
            continue
        elif "+-" in mystr:
            mystr=re.sub("\+-","-",mystr)
            continue
        else:
            return mystr
def mydeal(mystr):
    c = re.search("\([^()]+\)", mystr)  # 找到第一个符合条件的值并赋值给c
    # print(c.group(), type(c.group()))  # (-40/5) <class ‘str‘>
    d = re.split("[()]", c.group())
    e = "".join(d)  # 将获得的值得括号去掉
    # print(e, type(e))  # 40/5 <class ‘str‘>
    f = calculate(e)  # 获得计算结果
    # print(f)
    g = c.group().replace("(", "\(").replace(")", "\)").replace("*","\*").replace("+","\+")#将元字符进行转义
    # print(g)  # \(-40/5\)
    h = re.sub(g, str(f), mystr)  #将计算结果替换到原来的公式中
    # print(h)  # 1-2*((60-30+-8.0*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))
    return h
# print(mydeal("1-2*((60-30+(-40/5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))"))
# print(mydeal("1-2*((60-30+-8.0*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))"))

while True: formula=input("请输入你要计算的公式: ".strip()) a = re.split(" ", formula) b = "".join(a) # 将公式中的空格全部去掉 # formula="1-2*((60-30+(-40/5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))" while True: if "(" in b: print("简化的公式如下:") b=change(b) b=mydeal(b) print(b) else: print("计算结果:") print(calculate(b)) break

输出结果如下:

请输入你要计算的公式: 1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )
简化的公式如下:
1-2*((60-30+-8.0*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))
简化的公式如下:
1-2*((60-30-8.0*173545.88095238098)-(-4*3)/(16-3*2))
简化的公式如下:
1-2*(-1388337.0476190478-(-4*3)/(16-3*2))
简化的公式如下:
1-2*(-1388337.0476190478--12/(16-3*2))
简化的公式如下:
1-2*(-1388337.0476190478+12/10)
简化的公式如下:
1-2*-1388335.8476190479
计算结果:
2776672.6952380957

 

Day.9计算器小程序

标签:type   运算   --   orm   赋值   实现   return   元字符   pytho   

原文地址:http://www.cnblogs.com/lxyoung/p/6789296.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!