计算器

import re,time

# 1.先循环括号
# 2.算括号的乘除,后算加减


s ='1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )'

def reduce_sysbol(name):        #"+-" 或 "-+"  换成-
    if re.search("(\+\-|\-\+|\-\-)",name):
        return re.sub("(\+\-|\-\+|\-\-)","-",name)
    return name


def calculation(front,sign,back):
    if sign == "*":
        return (float(front) * float(back))
    elif sign == "/":
        return (float(front) / float(back))
    elif sign == "+":
        return (float(front) + float(back))
    else:
        return (float(front) - float(back))


def priority(name):
    obj = name.strip("()")   #两边括号取消
    obj = reduce_sysbol(obj)
    while True:
        if re.search("(?P<front>\d+\.*\d*)(?P<sign>[*/])(?P<back>\-*\d+\.*\d*)",obj):  #先找乘除
            a  = re.search("(?P<front>\d+\.*\d*)(?P<sign>[*/])(?P<back>\-*\d+\.*\d*)",obj)
            b = calculation(a.group("front"),a.group("sign"),a.group("back"))
            obj = obj.replace(a.group(),str(b))
            continue
        elif re.search("(?P<front>\-*\d+\.*\d*)(?P<sign>[+-])(?P<back>\-*\d+\.*\d*)",obj):
            a = re.search("(?P<front>\-*\d+\.*\d*)(?P<sign>[+-])(?P<back>\-*\d+\.*\d*)",obj)
            b = calculation(a.group("front"), a.group("sign"), a.group("back"))
            obj = obj.replace(a.group(), str(b))
        else:
            return obj

def run(arg):
    obj = arg.replace(" ", "")
    while True:
        if re.search("\([^()]+\)",obj):         #找括号里面没有括号的
            sea_brackets = re.search("\([^()]+\)",obj)
            jieguo = priority(sea_brackets.group())
            obj = obj.replace(sea_brackets.group(),str(jieguo))
        else:
            jieguo = priority(obj)
            if re.search("^\-*\d+\.*\d*",obj):
                print(jieguo)
                exit()
            obj = obj.replace(sea_brackets.group(),str(jieguo))
            print(obj)


if __name__ == '__main__':
    run(s)

  

posted @ 2017-05-01 17:11  golangav  阅读(322)  评论(0编辑  收藏  举报