本文实例讲述了Python3.6基于正则实现的计算器。分享给大家供大家参考,具体如下:
# -*- coding:utf-8 -*-#!python3import reimport copydef my_calc(inside): """ 计算括号内的算术式 :param inside:算术式 :return:结果 """ while True: # 1、首先需要把含有优先级最高的*和/找出来 # 这里有几种情况,(1*1) (1*-1) (-1*1)除法类似(暂时不考虑分母为0的情况) # 但是有了正则就方便多了 search_ret = re.search('(/(-)?/d+(/./d+)?[*/]-?/d+(/./d+)?', inside) if search_ret is None: break ret_str = search_ret.group() if '(' in ret_str: ret_str = ret_str[1:] num_list = re.split('[*/]', ret_str) operator = re.search('[*/]', ret_str).group() calc_ret = 0 if operator == '*': calc_ret = float(num_list[0]) * float(num_list[1]) elif operator == '/': calc_ret = float(num_list[0]) / float(num_list[1]) inside = inside.replace(ret_str, str(calc_ret)) # */都运算完以后就可以做+-了 while True: # 2、把含有+-的算术式找出来 search_ret = re.search('(/(-)?/d+(/./d+)?[+/-]-?/d+(/./d+)?', inside) if search_ret is None: break ret_str = search_ret.group() if '(' in ret_str: ret_str = ret_str[1:] tmp_str = copy.copy(ret_str) num_1 = re.match('-?/d+(/./d+)?', tmp_str).group() tmp_str = tmp_str.replace(num_1, '') operator = tmp_str[0] num_2 = tmp_str[1:] calc_ret = 0 if operator == '+': calc_ret = float(num_1) + float(num_2) elif operator == '-': calc_ret = float(num_1) - float(num_2) inside = inside.replace(ret_str, str(calc_ret)) return re.sub('[()]', '', inside)def format_str(s): s = s.replace('--', '+') s = s.replace('-+', '-') s = s.replace('++', '+') s = s.replace('+-', '-') if s[0] == '+': s = s[1:] s = '('+s+')' return sdef un_bracket_calc(final_str): # -1*2+3-4/-5 final_str = format_str(final_str) final_str = my_calc(final_str) return final_strdef my_math(s): # "((-1-2*-3)/(3-2)+(9*5-89)*(2*3*(3-0)))" while True: inside_bracket = re.search('[()]+[()]+', s) if inside_bracket is None: # 括号都算完了,如果还有算术式继续运算 s = un_bracket_calc(s) break src_str = inside_bracket.group() ret = my_calc(src_str) s = s.replace(src_str, ret) return ss_src = "((-1 - 2 * -3) / (3 - 2) + (9 * 5 - 9) * (2 * 3 * (3 - 0))) * -100 + 99-100 * -1-1"s_src = s_src.replace(' ', '')print(my_math(s_src))s_ret = ((-1 - 2 * -3) / (3 - 2) + (9 * 5 - 9) * (2 * 3 * (3 - 0))) * -100 + 99 - 100 * -1 - 1print(s_ret)
运行结果:
PS:这里再为大家推荐几款计算工具供大家进一步参考借鉴:
在线一元函数(方程)求解计算工具:
http://tools.jb51.net/jisuanqi/equ_jisuanqi
科学计算器在线使用_高级计算器在线计算:
新闻热点
疑难解答