计算器

第一版

import re


def mult_div_fn(l):  return float(l[0]) if len(l) == 1 else ( #乘除法运算
        mult_div_fn(l[:-2]) * float(l[-1]) if l[-2:-1][0] == "*" else mult_div_fn(l[:-2]) / float(l[-1]))


def add_sub_fn(l): return float(l[0]) if len(l) == 1 else add_sub_fn(l[:-1]) + float(l[-1])  # 加减法运算


s = '1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )'.replace(" ", "")
bracket = re.compile("\([^()]+\)")  # 找出最里面的括号的表达式
m_d = re.compile("\d+(?:\.\d+)?(?:[*/]-?\d+(?:\.\d+)?)+")  # 找出有乘除的表达式 如7 /3*99/4*2998
m_d_split = re.compile("((?:-?\d+(?:\.\d+)?)|[*/])")  # 分离乘除计算符与数字如将[4*5]分离为[4,*,5]
a_s_split = re.compile("[+-]?\d+(?:\.\d+)?")  # 将每个数字与他前面的加减符号一起匹配出来 如将[-2+3-4]分离为[-2,+3,-4]


def oper_four(i):
    for n in m_d.findall(i):
        i = i.replace(n, str(mult_div_fn(m_d_split.findall(n)))).replace("+-", "-").replace("--", "+")# 乘除法
    return str(add_sub_fn(a_s_split.findall(i)))  # 处理加减法


while bracket.findall(s):  # 如果有括号
    for i in bracket.findall(s):
        s = s.replace(i, oper_four(i)).replace("+-", "-").replace("--", "+")
print(oper_four(s))

第二版

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) )'.replace(" ", "")
bracket = re.compile("\([^()]+\)")  # 最里面的括号
mult_div = re.compile("\d+(?:\.\d+)?[*/]-?\d+(?:\.\d+)?")  # 两个数乘除表达式
add_sub = re.compile("\-?\d+(\.\d+)?[+-]\d+(\.\d+)?")  # 两个数加减表达
m_d_split = re.compile("((?:-?\d+(?:\.\d+)?)|[*/])")  # 分离乘除计算符与数字如将[4*5]分离为[4,*,5]
a_s_split = re.compile("[+-]?\d+(?:\.\d+)?")  # 将每个数字与他前面的加减符号一起匹配出来 如将[-2+3-4]分离为[-2,+3,-4]


def m_d(l):
    return float(l[0]) * float(l[2]) if l[1] == "*" else float(l[0]) / float(l[2])


def four_operator(s, flag=True):  # falg是表达式有没有括号的标识
    while mult_div.search(s):
        ret = mult_div.search(s).group()
        l = m_d_split.findall(ret)
        s = s.replace(ret, str(m_d(l))).replace("+-", "-").replace("--", "+")
    while add_sub.search(s):
        ret = add_sub.search(s).group()
        l = a_s_split.findall(ret)
        s = s.replace(ret, str(float(l[0]) + float(l[1])))
    return s[1:-1].replace("+-", "-").replace("--", "+") if flag else float(s)  # 返回去掉括号的字符串,如果表达式没有括号,返回值


while bracket.search(s):
    ret = bracket.search(s).group()
    s = s.replace(ret, four_operator(ret))
print(four_operator(s, False))

 

posted @ 2018-07-17 10:38  显示名称已经被使用  阅读(590)  评论(3编辑  收藏  举报