• python实现计算器功能


     1 import re
     2 
     3 
     4 def strip_operate(exp):    # 合并多余的操作符
     5     exp = exp.replace("+-", "-")
     6     exp = exp.replace("--", "+")
     7     return exp  
     8 
     9 
    10 def cal_exp_son(exp_son):    # 计算两数的乘除
    11     if "/" in exp_son:
    12         a, b = exp_son.split("/")
    13         return str(float(a)/float(b))
    14     elif "*" in exp_son:
    15         a, b = exp_son.split("*")
    16         return str(float(a)*float(b))
    17 
    18 
    19 def cal_no_bracket(exp):    # 计算一个里面已经没有括号的式子
    20     exp = exp.strip("()")
    21     while True:
    22         ret1 = re.search(r"d+.?d*[/*]-?d+.?d*", exp)
    23         if ret1:     # 先乘除
    24             exp_son = ret1.group()
    25             ret2 =cal_exp_son(exp_son)
    26             exp = exp.replace(exp_son, ret2)
    27             exp = strip_operate(exp)
    28         else:      # 后加减
    29             ret4 = re.findall(r"-?d+.?d*", exp)
    30             sum1 = 0
    31             for i in ret4:
    32                 sum1 += float(i)
    33             return str(sum1)
    34 
    35 
    36 def main_1(express):
    37     while True:
    38         ret = re.search(r"([^()]+)", express)
    39         if ret:
    40             express_no_bracket = ret.group()    
    41             ret3 = cal_no_bracket(express_no_bracket)
    42             express = express.replace(express_no_bracket, ret3)
    43             express = strip_operate(express)
    44         else:
    45             ret4 = cal_no_bracket(express)
    46             return ret4
    47 
    48 
    49 express = '1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )'
    50 express = express.replace(" ", "")
    51 ret5 = main_1(express)
    52 print(ret5)
  • 相关阅读:
    RTX Server license update
    Dell Raid[转载]
    Dell2950 server OS Installation
    Paragon Partition Manager 9.0 Professional管理磁盘分区
    Upgrade Backup Exec License
    C# 3.0将偷懒进行到底
    hibernate学习笔记
    开发c#插件
    Socket简单通讯
    .NET牛人应该知道些什么(转)?
  • 原文地址:https://www.cnblogs.com/nxrs/p/10425488.html
Copyright © 2020-2023  润新知