Python 练习: 计算器

匿名 (未验证) 提交于 2019-12-02 22:51:30
import re  def format_string(s):             # 对表达式进行格式化     s = s.replace(' ', '')     s = s.replace("--", "+")     s = s.replace("++", "+")     s = s.replace("+-", "-")     s = s.replace("*+", "*")     s = s.replace("/+", "/")     return s   def check_expression(s):          # 对表达式进行检测     flag = True     if not s.count("(") == s.count(")"):         print("括号没有闭合")         flag = False     if re.findall('[a-z]+', s.lower()):         print("有非法字符")         flag = False      return flag   def calc_mul_div(s):     regular = '[\-]?\d+\.?\d*[*/][\-]?\d+\.?\d*'      while re.findall(regular, s):         expression = re.search(regular, s).group()          if expression.count("*"):          # 判断是否是乘法             x, y = expression.split("*")             mul_result = str(float(x) * float(y))             s = s.replace(expression, mul_result)             s = format_string(s)          if expression.count("/"):          # 判断是否是除法             x, y = expression.split('/')             div_result = str(float(x) / float(y))             s = s.replace(expression, div_result)             s = format_string(s)      return s   def calc_add_sub(s):                       # 判断加减法     add_regular = '[\-]?\d+\.?\d*\+[\-]?\d+\.?\d*'     sub_regular = '[\-]?\d+\.?\d*\-[\-]?\d+\.?\d*'      while re.findall(add_regular, s):         add_list = re.findall(add_regular, s)         for add_str in add_list:             x, y = add_str.split("+")             add_result = "+" + str(float(x) + float(y))             s = s.replace(add_str, add_result)         s = format_string(s)      while re.findall(sub_regular, s):         sub_list = re.findall(sub_regular, s)         for sub_str in sub_list:             numbers = sub_str.split("-")             if len(numbers) == 3:      # 如果表达式类似 -1-1,则 list 是 ['', '1', '1'] ,                                        # 如果表达式类似 8-2, 则 list 是 ['8', '2']                 result = 0                 for v in numbers:                     if v:                         result -= float(v)             else:                 x, y = numbers                 result = float(x) - float(y)             s = s.replace(sub_str, "+" + str(result))         s = format_string(s)      return s   if __name__ == "__main__":     s = '(( 2 /1 * 7 ) - ( 3 *4 ) )'      if check_expression(s):         s = format_string(s)          while s.count("(") > 0:             strs = re.search('\([^()]*\)', s).group()             replace_str = calc_mul_div(strs)              replace_str = calc_add_sub(replace_str)              s = format_string(s.replace(strs, replace_str[1:-1]))  # 去掉多余的括号          else:             replace_str = calc_mul_div(s)              replace_str = calc_add_sub(replace_str)              s = s.replace(s, replace_str)          print("result: ", s.replace("+", ""))   运行结果: result:  2.0
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!