利用正则进行运算规则的计算

版本一:

# import re
#
# ss = '1 - 2 * ((60 - 30 + (-40/5) * (9 - 2 * 5 / 3 + 7 / 3 * 99 / 4 * 2998 + 10 * 568 / 14)) - (-4 * 3) / (16 - 3 * 2))'
#
# print(re.search('\([^\(]+\)', ss).group())
#
# def check(s):
# flag = True
# if re.findall('[a-zA-Z]', s):
# print('Invalid')
# flag = False
# return flag
#
# def check_format(s):
# s = s.replace(' ', '')
# s = s.replace('++', '+')
# s = s.replace('--', '+')
# s = s.replace('-+', '-')
# return s
# # 计算乘法,除法
# def cal_mul_div(s): # 匹配小数,多位数字 (2+3.2*5.6)
# # 返回乘法的结果
# str1 = re.search('\d+\.?\d*[*/]\d+\.?\d*', s).group()
# # 3.2 5.6 *进行切割
# x, y = re.split('[*/]', str) #x='3.2', y='5.6'
# if str.find('.'):
# ret2 = float(x) * float(y)
# str(ret2)
# else:
# ret2 = int(x) * int(y)
# str(ret2)
# s.replace(str1, ret2)
# return s
#
#
#
# return s # 2 + 15
#
#
# def cal_add_sub(s): # s=2+15
#
#
# if check(ss):
# str = check_format(ss)
# while re.search('\(', str):
# # 1-2*((60-30+(-40/5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))
# strs = re.search('\([^\(]+\)', ss).group()
# str = cal_mul_div(str) # 2+25
# s = cal_add_sub(str) # (27)
#
# else:
#
# else:
# print('no')
# #!/usr/bin/python27
#_*_ coding=utf-8 _*_ '''
该计算器思路:
1、递归寻找表达式中只含有 数字和运算符的表达式,并计算结果
2、由于整数计算会忽略小数,所有的数字都认为是浮点型操作,以此来保留小数
使用技术:
1、正则表达式
2、递归 执行流程如下:
******************** 请计算表达式: 1 - 2 * ( (60-30 +(-40.0/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) ) ********************
before: ['1-2*((60-30+(-40.0/5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))']
-40.0/5=-8.0
after: ['1-2*((60-30+-8.0*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))']
========== 上一次计算结束 ==========
before: ['1-2*((60-30+-8.0*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))']
9-2*5/3+7/3*99/4*2998+10*568/14=173545.880953
after: ['1-2*((60-30+-8.0*173545.880953)-(-4*3)/(16-3*2))']
========== 上一次计算结束 ==========
before: ['1-2*((60-30+-8.0*173545.880953)-(-4*3)/(16-3*2))']
60-30+-8.0*173545.880953=-1388337.04762
after: ['1-2*(-1388337.04762-(-4*3)/(16-3*2))']
========== 上一次计算结束 ==========
before: ['1-2*(-1388337.04762-(-4*3)/(16-3*2))']
-4*3=-12.0
after: ['1-2*(-1388337.04762--12.0/(16-3*2))']
========== 上一次计算结束 ==========
before: ['1-2*(-1388337.04762--12.0/(16-3*2))']
16-3*2=10.0
after: ['1-2*(-1388337.04762--12.0/10.0)']
========== 上一次计算结束 ==========
before: ['1-2*(-1388337.04762--12.0/10.0)']
-1388337.04762--12.0/10.0=-1388335.84762
after: ['1-2*-1388335.84762']
========== 上一次计算结束 ==========
我的计算结果: 2776672.69524
'''

版本二:


import re,os,sys def compute_exponent(arg):
""" 操作指数
:param expression:表达式
:return:计算结果
""" val = arg[0]
pattern = re.compile(r'\d+\.?\d*[\*]{2}[\+\-]?\d+\.?\d*')
mch = pattern.search(val)
if not mch:
return
content = pattern.search(val).group() if len(content.split('**'))>1:
n1, n2 = content.split('**')
value = float(n1) ** float(n2)
else:
pass before, after = pattern.split(val, 1)
new_str = "%s%s%s" % (before,value,after)
arg[0] = new_str
compute_exponent(arg) def compute_mul_div(arg):
""" 操作乘除
:param expression:表达式
:return:计算结果
""" val = arg[0]
pattern = re.compile(r'\d+\.?\d*[\*\/\%\/\/]+[\+\-]?\d+\.*\d*')
mch = pattern.search(val)
if not mch:
return
content = pattern.search(val).group() if len(content.split('*'))>1:
n1, n2 = content.split('*')
value = float(n1) * float(n2)
elif len(content.split('//'))>1:
n1, n2 = content.split('//')
value = float(n1) // float(n2)
elif len(content.split('%'))>1:
n1, n2 = content.split('%')
value = float(n1) % float(n2)
elif len(content.split('/'))>1:
n1, n2 = content.split('/')
value = float(n1) / float(n2)
else:
pass before, after = pattern.split(val, 1)
new_str = "%s%s%s" % (before,value,after)
arg[0] = new_str
compute_mul_div(arg) def compute_add_sub(arg):
""" 操作加减
:param expression:表达式
:return:计算结果
"""
while True:
if arg[0].__contains__('+-') or arg[0].__contains__("++") or arg[0].__contains__('-+') or arg[0].__contains__("--"):
arg[0] = arg[0].replace('+-','-')
arg[0] = arg[0].replace('++','+')
arg[0] = arg[0].replace('-+','-')
arg[0] = arg[0].replace('--','+')
else:
break if arg[0].startswith('-'): arg[1] += 1
arg[0] = arg[0].replace('-','&')
arg[0] = arg[0].replace('+','-')
arg[0] = arg[0].replace('&','+')
arg[0] = arg[0][1:]
val = arg[0] pattern = re.compile(r'\d+\.?\d*[\+\-]{1}\d+\.?\d*')
mch = pattern.search(val)
if not mch:
return
content = pattern.search(val).group()
if len(content.split('+'))>1:
n1, n2 = content.split('+')
value = float(n1) + float(n2)
else:
n1, n2 = content.split('-')
value = float(n1) - float(n2) before, after = pattern.split(val, 1)
new_str = "%s%s%s" % (before,value,after)
arg[0] = new_str
compute_add_sub(arg) def compute(expression):
""" 操作加减乘除
:param expression:表达式
:return:计算结果
"""
inp = [expression,0] # 处理表达式中的指数
compute_exponent(inp) # 处理表达式中的乘除求余等
compute_mul_div(inp) # 处理表达式的加减
compute_add_sub(inp)
if divmod(inp[1],2)[1] == 1:
result = float(inp[0])
result = result * -1
else:
result = float(inp[0])
return result def exec_bracket(expression):
""" 递归处理括号,并计算
:param expression: 表达式
:return:最终计算结果
"""
pattern = re.compile(r'\(([\+\-\*\/\%\/\/\*\*]*\d+\.*\d*){2,}\)')
# 如果表达式中已经没有括号,则直接调用负责计算的函数,将表达式结果返回,如:2*1-82+444
#if not re.search('\(([\+\-\*\/]*\d+\.*\d*){2,}\)', expression):
if not pattern.search(expression):
final = compute(expression)
return final
# 获取 第一个 只含有 数字/小数 和 操作符 的括号
# 如:
# ['1-2*((60-30+(-40.0/5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))']
# 找出:(-40.0/5)
content = pattern.search(expression).group() # 分割表达式,即:
# 将['1-2*((60-30+(-40.0/5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))']
# 分割更三部分:['1-2*((60-30+( (-40.0/5) *(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))']
before, nothing, after = pattern.split(expression, 1) print('before:',expression)
content = content[1:len(content)-1] # 计算,提取的表示 (-40.0/5),并活的结果,即:-40.0/5=-8.0
ret = compute(content) print('%s=%s' %( content, ret)) # 将执行结果拼接,['1-2*((60-30+( -8.0 *(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))']
expression = "%s%s%s" %(before, ret, after)
print('after:',expression)
print("="*10,'previous result is',"="*10) # 循环继续下次括号处理操作,本次携带者的是已被处理后的表达式,即:
# ['1-2*((60-30+ -8.0 *(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))'] # 如此周而复始的操作,直到表达式中不再含有括号
return exec_bracket(expression) # 使用 __name__ 的目的:
# 只有执行 python index.py 时,以下代码才执行
# 如果其他人导入该模块,以下代码不执行
if __name__ == "__main__":
flag = True os.system('clear') print('\n================================================================')
print('\033[33m 欢迎使用计算器 :\033[0m')
print('\n================================================================') while flag:
calculate_input = input('\033[32m请输入计算的表达式 | (退出:q)\033[0m')
calculate_input = re.sub('\s*','',calculate_input)
if len(calculate_input) == 0:
continue
elif calculate_input == 'q':
sys.exit('退出程序')
elif re.search('[^0-9\.\-\+\*\/\%\/\/\*\*\(\)]',calculate_input):
print('\033[31m 输入错误,请重新输入!!!\033[0m')
else:
result = exec_bracket(calculate_input)
print('the expression result is %s' % result)
[代码来自网络,仅供学习]
 【更多参考】

Java实例---计算器实例

Python实例---利用正则实现计算器[参考版]的更多相关文章

  1. Python实例---利用正则实现计算器[FTL版]

    import re # 格式化 def format_str(str): str = str.replace('--', '+') str = str.replace('-+', '-') str = ...

  2. Python开发——利用正则表达式实现计算器算法

    Python开发--利用正则表达式实现计算器算法 (1)不使用eval()等系统自带的计算方法 (2)实现四则混合运算.括号优先级解析 思路: 1.字符串预处理,将所有空格去除 2.判断是否存在括号运 ...

  3. 【Python】利用正则解析xml练习题

    { "date": "18-03-29 06:04:47", "data": { "deviceType": 1, &q ...

  4. python模块之正则

    re模块 可以读懂你写的正则表达式 根据你写的表达式去执行任务 用re去操作正则 正则表达式 使用一些规则来检测一些字符串是否符合个人要求,从一段字符串中找到符合要求的内容.在线测试网站:http:/ ...

  5. Python 2.7_爬取CSDN单页面利用正则提取博客文章及url_20170114

    年前有点忙,没来的及更博,最近看爬虫正则的部分 巩固下 1.爬取的单页面:http://blog.csdn.net/column/details/why-bug.html 2.过程 解析url获得网站 ...

  6. python面试题300道答案参考1

    提示 自己整合的答案,虽有百家之所长,仍很局限,如有需要改进的地方,或者有更好的答案,欢迎提出! [合理利用 Ctrl+F 提高查找效率] 文章来源    https://www.cnblogs.co ...

  7. (转)Python实例手册

    原文地址:http://hi.baidu.com/quanzhou722/item/cf4471f8e23d3149932af2a7 实在是太好的资料了,不得不转 python实例手册 #encodi ...

  8. JS利用正则配合replace替换指定字符

    替换指定字符的方法有很多,在本文为大家详细介绍下,JS利用正则配合replace是如何做到的,喜欢的朋友可以参考下 定义和用法 replace() 方法用于在字符串中用一些字符替换另一些字符,或替换一 ...

  9. 转载 python实例手册

    python实例手册 #encoding:utf8# 设定编码-支持中文 0说明 手册制作: 雪松 更新日期: 2013-12-19 欢迎系统运维加入Q群: 198173206 # 加群请回答问题 请 ...

随机推荐

  1. android逆向基础:apk 反编译 重打包 重签名

    apk 反编译大家都比较熟悉,这里只做一个笔记. 1 反编译 apk apktool d perfect.apk 这样就把资源文件解压缩了, classes.dex 也反编译成了 smali 文件 2 ...

  2. JavaScript数据结构-17.图结构

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...

  3. "Visual Studio Code is unable to watch for file changes in this large workspace"

    https://code.visualstudio.com/docs/setup/linux#_visual-studio-code-is-unable-to-watch-for-file-chang ...

  4. ES6常用七大特性

    ES6可谓是对JS语言的一个颠覆性改变,增加了Module改善JS一直被诟病的模块化.Promise解决异步函数的回调地狱.Class的面相对象编程... 在学习ES6的过程中,大家或多或少都有看过阮 ...

  5. Codeforces F. Cowmpany Cowmpensation

    Description 有一棵树,现在要给每个节点赋一个在1到D之间的权值,问有多少种方案满足任意一个节点的权值都不大于其父亲的权值. n<=3000,D<=1e9 题面 Solution ...

  6. Simotion 监控问题:Could not add self-signed certificate to certificate store.

    使用OPC UA 连接设备,在创建客户端证书时总是报这个错误:Could not add self-signed certificate to certificate store.. 解决方法,用管理 ...

  7. webpack 报错 No PostCSS Config found 解决方案。

    webpack 报错 No PostCSS Config found  这个问题我在百度上找了好久,也没有找到解决方案,最后没有办法只能自己去啃官方文档,本案例在本人的webpack 学习感悟中已经写 ...

  8. Orchard源码:EventBus&EventHandler

    概述 看源码是一件吃力又很爽的事情,昨天还被搞的一头雾水,今天忽然守得云开见月明.明白它设计意图的同时,感觉自己又提升了一步:) Orchard刚开始看往往毫无头绪,建议可以从Orchard.Fram ...

  9. js post跳转

    function clickFunc(id) { var params = new Array(); params.push({ name: "id", value: id}); ...

  10. SQL Server使用ROW_NUMBER进行快速分页查询

    DECLARE @pageSize INTDECLARE @pageIndex INT --第4页,每页显示10条数据SET @pageSize = 10SET @pageIndex = 4 SELE ...