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

计算器代码

时间:2017-12-25 00:43:19      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:--   one   pass   span   not   str   gpo   arc   except   

代码比较low,有时间在更新。

当时初学只是为了实现。

#实现加减乘除以及括号优先级解析))

import re

s = "1-2*((60-30+(-40/5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))"
# s = "1-2*((60-30-8*(9-3+146902+405))-(-4*3)/(16-3*2))"
print(eval(s))


def retr(str):
    try:
        str = str.replace("--", "+")
        str = str.replace("++", "+")
        str = str.replace("-+", "-")
        str = str.replace("+-", "-")
    except:
        pass

    ret = re.search("\([^()]+\)", str)

    a = ret.group()
    print(a)
    if ret == None:
        pass
    else:
        suan = ret.group()
        suan = suan.replace("(", "")
        suan = suan.replace(")", "")
    return suan,a

# def th(str):

def hf(str):
    a = str[:2]
    if not a.isdigit():
        if a == "-+" or a == "+-":
            str = str.replace(a, "-")
    return str

def jjcc(str):
    nstr = hf(str)
    ret = re.search("(.*?\d+)(\D)(.*?\d+)", nstr)
    # print(ret.group())
    a = ret.group(2)
    c = int(ret.group(1))
    b = int(ret.group(3))
    if a == "+":
        end = c + b
    if a == "-":
        end = c - b
    if a == "*":
        end = c * b
    if a == "/":
        end = c / b
    return end

# print(jjcc(suan))
# print(jjcc("-+6*-1"))


# while True:
#     suan, a = retr(s)[0],retr(s)[1]
#     rep = str(jjcc(suan))
#     s = s.replace(a, rep)
#     print(s)

suan, a = retr(s)[0], retr(s)[1]
rep = str(jjcc(suan))
s = s.replace(a, rep)
# print(s)

suan, a = retr(s)[0], retr(s)[1]
rep = str(jjcc(suan))
s = s.replace(a, rep)
# print(s)

 

计算器代码

标签:--   one   pass   span   not   str   gpo   arc   except   

原文地址:http://www.cnblogs.com/GhostCatcg/p/8099632.html

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