利用正则实现计算器

利用正则来实现简单计算器的功能,能够设计计算带括号的加减乘除运算。当然不使用eval等语句。

利用递归:

import re
from functools import reduce
def foo2(y):
if '(' in y:
t1 = re.search(r'\([^()]+\)',y)
temp1 = t1.group().strip('()')
res = foo1(temp1)
y = y.replace(t1.group(),str(res))
return foo2(y)
else:
return foo1(y)
def foo1(x):
x = x.replace(' ','')
if x.find('*') == -1 and x.find('/') == -1:
res = str(foo3(x))
return res
else:
t1 = re.search(r'(?P<x1>(-?\d+\.\d*)|(-?\d+))(?P<x2>\*|\/)(?P<x3>(-?\d+\.\d*)|(-?\d+))',x)
t2 = re.search(r'((-?\d+\.\d*)|(-?\d+))(\*|\/)((-?\d+\.\d*)|(-?\d+))',x)
y1 = float(t1.group('x1')) if '.' in t1.group('x1') else int(t1.group('x1'))
y2 = float(t1.group('x3')) if '.' in t1.group('x3') else int(t1.group('x3'))
temp = y1 * y2 if t1.group('x2') == '*' else y1 / y2
tt = '+' + str(temp) if y1 < 0 and temp > 0 else str(temp)
x = x.replace(t2.group(),tt)
return foo1(x)
def foo3(z):
z = z.replace(' ','')
z = re.sub('\+\-|\-\+','-',z)
z = re.sub('\-\-|\+\+','+',z)
z = re.findall('-?\d+\.\d*|-?\d+',z)
z = list(map(lambda x: float(x) if '.' in x else int(x), z))
res = reduce(lambda x,y:x+y,z)
return res
while True:
s = input('please input :> ')
print('the result is %s' %foo2(s))

利用循环:

import re
from functools import reduce
def foo2(y):
while '(' in y:
t1 = re.search(r'\([^()]+\)',y)
temp1 = t1.group().strip('()')
res = foo1(temp1)
y = y.replace(t1.group(),str(res))
return foo1(y)
def foo1(x):
x = x.replace(' ','')
while x.find('*') != -1 or x.find('/') != -1:
t1 = re.search(r'(?P<x1>(-?\d+\.\d*)|(-?\d+))(?P<x2>\*|\/)(?P<x3>(-?\d+\.\d*)|(-?\d+))',x)
t2 = re.search(r'((-?\d+\.\d*)|(-?\d+))(\*|\/)((-?\d+\.\d*)|(-?\d+))',x)
y1 = float(t1.group('x1')) if '.' in t1.group('x1') else int(t1.group('x1'))
y2 = float(t1.group('x3')) if '.' in t1.group('x3') else int(t1.group('x3'))
temp = y1 * y2 if t1.group('x2') == '*' else y1 / y2
tt = '+' + str(temp) if y1 < 0 and temp > 0 else str(temp)
x = x.replace(t2.group(),tt)
return str(foo3(x))
def foo3(z):
z = z.replace(' ','')
z = re.sub('\+\-|\-\+','-',z)
z = re.sub('\-\-|\+\+','+',z)
z = re.findall('-?\d+\.\d*|-?\d+',z)
z = list(map(lambda x: float(x) if '.' in x else int(x), z))
res = reduce(lambda x,y:x+y,z)
return res
while True:
s = input('please input :> ')
print('the result is %s' %foo2(s))

python正则实现简单计算器的更多相关文章

  1. Python之实现简单计算器功能

    一,需求分析 要求计算一串包含数字+-*/()的类似于3*( 4+ 50 )-(( 100 + 40 )*5/2- 3*2* 2/4+9)*((( 3 + 4)-4)-4)表达式的数值 二,知识点 正 ...

  2. Python正则简单实例分析

    Python正则简单实例分析 本文实例讲述了Python正则简单用法.分享给大家供大家参考,具体如下: 悄悄打入公司内部UED的一个Python爱好者小众群,前两天一位牛人发了条消息: 小的测试题:  ...

  3. 用Python写一个简单的Web框架

    一.概述 二.从demo_app开始 三.WSGI中的application 四.区分URL 五.重构 1.正则匹配URL 2.DRY 3.抽象出框架 六.参考 一.概述 在Python中,WSGI( ...

  4. Python正则式的基本用法

    Python正则式的基本用法 1.1基本规则 1.2重复 1.2.1最小匹配与精确匹配 1.3前向界定与后向界定 1.4组的基本知识 2.re模块的基本函数 2.1使用compile加速 2.2 ma ...

  5. hiho #1332 : 简单计算器 栈+递归

    #1332 : 简单计算器 时间限制:10000ms 单点时限:1000ms 内存限制:256MB 描述 编写一个程序可以完成基本的带括号的四则运算.其中除法(/)是整除,并且在负数除法时向0取整.( ...

  6. 认识python正则模块re

    python正则模块re python中re中内置匹配.搜索.替换方法见博客---python附录-re.py模块源码(含re官方文档链接) 正则的应用是处理一些字符串,phthon的博文python ...

  7. 1.C#WinForm基础制作简单计算器

    利用c#语言编写简单计算器: 核心知识点: MessageBox.Show(Convert.ToString(comboBox1.SelectedIndex));//下拉序号 MessageBox.S ...

  8. 菜鸟学Android编程——简单计算器《一》

    菜鸟瞎搞,高手莫进 本人菜鸟一枚,最近在学Android编程,网上看了一些视频教程,于是想着平时手机上的计算器应该很简单,自己何不尝试着做一个呢? 于是就冒冒失失的开撸了. 简单计算器嘛,功能当然很少 ...

  9. python 正则,常用正则表达式大全

    Nginx访问日志匹配 re.compile #re.compile 规则解释,改规则必须从前面开始匹配一个一个写到后面,前面一个修改后面全部错误.特殊标准结束为符号为空或者双引号:  改符号开始 从 ...

随机推荐

  1. poj1830:开关问题

    链接:http://poj.org/problem?id=1830 某天“佐理慧学姐”突然来问了我这道题. 诶,窝只会线性基,但是好像搞不了方案数啊…… 啃题解吧. woc!线性代数哦,就是那种我不会 ...

  2. POJ 3041 Asteroids(模板——二分最大匹配(BFS增广))

    题目链接: http://poj.org/problem?id=3041 Description Bessie wants to navigate her spaceship through a da ...

  3. DEDE在图集列表中调出图集的所有图片[首页也适用]

    在include/common.func.php 中添加以下函数代码 代码如下:   // 在图集列表中调出图集的所有图片 function Getimgs($aid, $imgwith = 220, ...

  4. php中urldecode()和urlencode()起什么作用啊

    urlencode()函数原理就是首先把中文字符转换为十六进制,然后在每个字符前面加一个标识符%. urldecode()函数与urlencode()函数原理相反,用于解码已编码的 URL 字符串,其 ...

  5. windows下如何创建没有名字的.htaccess文件

    http://www.mdaima.com/jingyan/35.html WINDOWS下建立空名的.htaccess文件 ? 大家都知道,在windows环境下是不能直接建立没有名字的文件的,那我 ...

  6. vue学习笔记(三)——目录结构介绍

    1.初始目录结构如下: 2.目录结构介绍 目录/文件 说明 build 最终发布的代码存放位置. config 配置目录,包括端口号等.我们初学可以使用默认的. node_modules npm 加载 ...

  7. 量化投资与Python之pandas

    pandas:数据分析 pandas是一个强大的Python数据分析的工具包.pandas是基于NumPy构建的. pandas的主要功能具备对其功能的数据结构DataFrame.Series集成时间 ...

  8. SpringMvc4.x--Spring MVC的常用注解

    //下列代码显示用到的对象public class DemoObj { private Long id; private String name; public DemoObj() { //① sup ...

  9. php连接memcahed出现Cannot assign requested address (99)的解决方法

    今天在将服务器合并后,发现php偶尔会报出 Server *.*.*.* (tcp *****) failed with: Cannot assign requested address (99) 的 ...

  10. 【javascript】onblur调用函数失效问题记录

    在处理页面上一个失焦效果时遇到了  xxxx is not a function 这样的错误,但函数确实有定义成功 ,经过测试发现是 id 值与函数名一致导致的问题,但是产生的原因没有找到详细的解释 ...