python实现简单的计算器功能

时间:2022-02-01 01:50:41

如想实现一个计算器的功能,输入格式为字符串,不能运用python里面的内置方法,出去简单的加减乘除,设计一个相对高级的计算器:

a = '1 - 2 * ( ( 6 0 -3 0  +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )'
# 去掉所有的空格
# 加减乘除 括号
# 先算括号里的乘除,再算括号里的加减
主要利用正则表达式来实现,具体代码如下:
import re
a = '1 - 2 * ( ( 6 0 -3 0  +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )'
res_brackets = re.compile(r'\([^\(\)]*\)') # 寻找带括号的(最内层的括号)
express = a.replace(' ','')
def dealwith(exp):
    '''
    deal with the formula
    :param exp: del_brackets data
    :return:
    '''
    exp = exp.replace('+-', '-')
    exp = exp.replace('--', '+')
    return exp
def add(exp):
    data = re.findall('\-?\d+\.?\d*',exp)
    sum_data = 0
    for i in data:
        sum_data += float(i)
    return str(sum_data)
def multi_divi(exp):
    '''
    calculate multiplication&division
    :param exp: res_multi_divi.search(del_brackets_data)
    :return:
    '''
    res_multi_divi = re.compile(r'\-?\d+\.?\d*[\*\/]\-?\d+\.?\d*')
    while res_multi_divi.search(exp):
        data = res_multi_divi.search(exp).group()
        if '*' in data:
            element = data.split('*')
            exp = exp.replace(data,str(float(element[0])*float(element[1])))
        if '/' in data:
            element = res_multi_divi.search(exp).group().split('/')
            exp = exp.replace(data, str(float(element[0]) / float(element[1])))
    else:
        return dealwith(exp)
def del_brackets(exp):
    while res_brackets.search(exp):
        brackets_data = res_brackets.search(exp).group()
        del_brackets_data = add(multi_divi(re.sub('\(|\)', '', brackets_data)))
        exp = dealwith(exp.replace(brackets_data,del_brackets_data))
    else:
        return add(multi_divi(exp))
print(del_brackets(express))

  当然,可以用更简单的代码来实现,但是思路基本一样。