用pathon实现计算器功能

实现计算类似公式的计算器程序
1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )
一.while循环版本
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=s.replace(' ','')
while '('in s and ')'in s:
    ret1 = re.search('\([^()]+\)', s).group()  #用search一个个的找括号里面的公式
    while 1:
        if '*' in ret1 or '/' in ret1:
            e, f = s.split(ret1)        #用括号里面的内容将公式切割
            # ret1 = ret1.lstrip('(').rstrip(')')    #去掉括号的左右俩边"()"
            ret2 = re.search('\d+(\.\d+)?[*/]-?\d+(\.\d+)?', ret1).group()    #用search一个个的找括号里面的公式的乘除法
            c,d=ret1.split(ret2)    #把括号里面的内容用乘除法切割
            if '*' in ret2:
                a,b=ret2.split('*')       #用符号切割得到两边的数字
                ret2=float(a)*float(b)            #将字符串转化成浮点数进行运算
                ret1=c + str(ret2) + d         #把运算结果再转回字符串拼接到括号里面
                s=e+ret1+f                  #把括号拼接到公式里
                print(s)
            elif '/' in ret2:
                a, b = ret2.split('/')
                ret2 = float(a) / float(b)
                ret1 = c + str(ret2) + d
                s=e+ret1+f
                print(s)
        else:break
    if '+' in ret1 or '-' in ret1:
        e, f = s.split(ret1)  # 用括号里面的内容将公式切割
        ret1 = ret1.lstrip('(').rstrip(')')  # 去掉括号的左右俩边"()"
        if '--' in s:
            s = s.replace('--', '+')
        if '-+' in s:
            s = s.replace('-+', '-')
        if '+-' in s:
            s = s.replace('+-', '-')
        if '++' in s:
            s = s.replace('++', '+')
        lst = re.findall('[+-]?\d+(?:\.\d+)?',ret1)  # 用findall找到所有的加减法,放到列表里
        print(lst)
        res = sum([float(i) for i in lst])
        s=e+str(res)+f
        print(s)
while '*' in s or '/' in s:      #计算括号外面的乘除法
    ret = re.search('\d+(\.\d+)?[*/]-?\d+(\.\d+)?',s).group()
    a,b=s.split(ret)
    if '*' in ret:
        c, d = ret.split('*')
        ret=float(c)*float(d)
        s = a +str(ret) + b
        print(s)
    elif '/' in ret:
        a, b = ret.split('/')
        ret= float(c)*float(d)
        s = a + str(ret) + b
        print(s)
if '--'in s:
    s=s.replace('--','+')
if '-+'in s:
    s=s.replace('-+','-')
if '+-'in s:
    s=s.replace('+-','-')
if '++'in s:
    s=s.replace('++','+')
lst=re.findall('[+-]?\d+(?:\.\d+)?',s)     #用findall找到所有的加减法,放到列表里
print(lst)
res=sum([float(i) for i in lst])
print(res)

  二,函数版本

 1 import re
 2 def mul_div(atom_exp):
 3     '''
 4     计算乘除法的表达式的函数
 5     :param atom_exp: a*b 或者 a/b的表达式
 6     :return: float数据类型的结果
 7     '''
 8     if '*' in atom_exp:
 9         a,b=atom_exp.split('*')
10         return float(a)*float(b)
11     elif '/' in atom_exp:
12         a, b = atom_exp.split('/')
13         return float(a) / float(b)
14 
15 def add_sub(no_bracket_exp):
16     '''
17     接收一个只有加减法的表达式,计算加减法并返回最终结果
18     :param no_bracket_exp: 只剩加减法的表达式
19     :return:floatt数据类型的结果
20     '''
21     ret_lst=re.findall('[-+]?\d+(?:\.\d+)?',no_bracket_exp)
22     sum_count=0
23     for num in ret_lst:
24         sum_count += float(num)
25     return sum_count
26 
27 def exp_format(exp):
28     '''
29     负责表达式的整理
30     :param exp: 接收的表达式可能含有 ++ -- +- -+ 等操作
31     :return: 返回一个没有重叠+-符号的表达式
32     '''
33     exp=exp.replace('--','+')
34     exp = exp.replace('+-', '-')
35     exp = exp.replace('-+', '-')
36     exp = exp.replace('++', '+')
37     return exp
38 def cal(no_bracket_exp):
39     '''
40     负责计算加减乘除
41     :param no_bracket_exp:一个内部不再有括号的表达式
42     :return: 最终计算的结果
43     '''
44     while 1:
45        ret=re.search('\d+(\.\d+)?[*/]-?\d+(\.\d+)?',no_bracket_exp)
46        if ret:
47             ret_exp=ret.group()
48             res=str(mul_div(ret_exp))
49             no_bracket_exp=no_bracket_exp.replace(ret_exp,res)
50        else:break
51     no_bracket_exp=exp_format(no_bracket_exp)
52     sum_count=add_sub(no_bracket_exp)
53     return sum_count
54 
55 def main(exp):
56     exp=exp.replace(' ','')
57     while 1:
58         ret=re.search('\([^()]+\)',exp)
59         if ret:
60             no_bracket_exp=ret.group()
61             ret=str(cal(no_bracket_exp))
62             exp=exp.replace(no_bracket_exp,ret)
63         else:break
64     return cal(exp)
65 
66 exp = '1 - 2 * ( (60-30 +  (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )* (-40/5)) - (-4*3)/ (16-3*2) )'
67 res=main(exp)
68 print(res)

猜你喜欢

转载自www.cnblogs.com/ppf3678/p/9997661.html