需求:

用户输入运算表达式,终端显示计算结果

源代码:

 # !/usr/bin/env/ python3
# -*- coding: utf-8 -*- """用户输入计算表达式,显示计算结果""" __author__ = 'Jack' import re bracket = re.compile(r'\([^()]+\)') # 寻找最内层括号规则
mul = re.compile(r'(\d+\.?\d*\*-\d+\.?\d*)|(\d+\.?\d*\*\d+\.?\d*)') # 寻找乘法运算规则
div = re.compile(r'(\d+\.?\d*/-\d+\.?\d*)|(\d+\.?\d*/\d+\.?\d*)') # 寻找除法运算规则
add = re.compile(r'(-?\d+\.?\d*\+-\d+\.?\d*)|(-?\d+\.?\d*\+\d+\.?\d*)') # 寻找加法运算规则
sub = re.compile(r'(-?\d+\.?\d*--\d+\.?\d*)|(-?\d+\.?\d*-\d+\.?\d*)') # 寻找减法运算规则
c_f = re.compile(r'\(?\+?-?\d+\)?') # 检查括号内是否运算完毕规则
strip = re.compile(r'[^(].*[^)]') # 脱括号规则 def Mul(s):
"""计算表达式中的乘法运算"""
exp = re.split(r'\*', mul.search(s).group())
return s.replace(mul.search(s).group(), str(float(exp[0]) * float(exp[1]))) def Div(s):
"""计算表达式中的除法运算"""
exp = re.split(r'/', div.search(s).group())
return s.replace(div.search(s).group(), str(float(exp[0]) / float(exp[1]))) def Add(s):
"""计算表达式中的加法运算"""
exp = re.split(r'\+', add.search(s).group())
return s.replace(add.search(s).group(), str(float(exp[0]) + float(exp[1]))) def Sub(s):
"""计算表达式中的减法运算"""
exp = sub.search(s).group()
if exp.startswith('-'): #如果表达式形如:-2.2-1.2;需变换为:-(2.2+1.2)
exp = exp.replace('-', '+') #将-号替换为+号;+2.2+1.2
res = Add(exp).replace('+', '-') #调用Add运算,将返回值+3.4变为-3.4
else:
exp = re.split(r'-', exp)
res = str(float(exp[0]) - float(exp[1]))
return s.replace(sub.search(s).group(), res) def calc():
while True:
s = input('Please input the expression(q for quit):') # 例:'1+2- (3* 4-3/2+ ( 3-2*(3+ 5 -3* -0.2-3.3*2.2 -8.5/ 2.4 )+10) +10)'
if s == 'q':
break
else:
s = ''.join([x for x in re.split('\s+', s)]) # 将表达式按空格分割并重组
if not s.startswith('('): # 若用户输入的表达式首尾无括号,则统一格式化为:(表达式)
s = str('(%s)' % s)
while bracket.search(s): # 若表达式s存在括号
s = s.replace('--', '+') # 检查表达式,并将--运算替换为+运算
s_search = bracket.search(s).group() # 将最内层括号及其内容赋给变量s_search
if div.search(s_search): # 若除法运算存在(必须放在乘法之前)
s = s.replace(s_search, Div(s_search)) # 执行除法运算并将结果替换原表达式
elif mul.search(s_search): # 若乘法运算存在
s = s.replace(s_search, Mul(s_search)) # 执行乘法运算并将结果替换原表达式
elif sub.search(s_search): # 若减法运算存在(必须放在加法之前)
s = s.replace(s_search, Sub(s_search)) # 执行减法运算并将结果替换原表达式
elif add.search(s_search): # 若加法运算存在
s = s.replace(s_search, Add(s_search)) # 执行加法运算并将结果替换原表达式
elif c_f.search(s_search): # 若括号内无任何运算(类似(-2.32)除外)
s = s.replace(s_search, strip.search(s_search).group()) # 将括号脱掉,例:(-2.32)---> -2.32 print('The answer is: %.2f' % (float(s))) if __name__ == '__main__':
calc()

使用正则表达式实现计算器功能

运行效果:

Python-正则表达式实现计算器功能的更多相关文章

  1. [ Python - 6 ] 正则表达式实现计算器功能

    要求:禁止使用eval函数.参考网上代码如下: #!_*_coding:utf-8_*_ """用户输入计算表达式,显示计算结果""" im ...

  2. Python+Tkinter 实现计算器功能

    #=================================================================================== import tkinter ...

  3. python 实现一个计算器功能

    #s = '1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )' #第 ...

  4. Python 正则实现计算器

    # !/usr/bin/env/ python3 # -*- coding: utf-8 -*- """用户输入计算表达式,显示计算结果""" ...

  5. 利用PYTHON设计计算器功能

    通过利用PYTHON 设计处理计算器的功能如: 1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 ))- (-4*3 ...

  6. 完成一段简单的Python程序,用于实现一个简单的加减乘除计算器功能

    #!/bin/usr/env python#coding=utf-8'''完成一段简单的Python程序,用于实现一个简单的加减乘除计算器功能'''try: a=int(raw_input(" ...

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

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

  8. 第11.13节 Python正则表达式的转义符”\”功能介绍

    为了支持特殊元字符在特定场景下能表示自身而不会被当成元字符进行匹配出来,可以通过字符集或转义符表示方法来表示,字符集表示方法前面在<第11.4节 Python正则表达式搜索字符集匹配功能及元字符 ...

  9. 第11.4节 Python正则表达式搜索字符集匹配功能及元字符”[]”介绍

    Python正则表达式字符集匹配表示是指搜索一个字符,该字符在给定的一个字符的集合中.元字符'['和']'是用于组合起来定义匹配字符集,匹配模式中使用 '['开头,并使用']'结尾来穷举搜索的字符可能 ...

随机推荐

  1. 7.pytest中的 plugin

    一直想弄弄清这里的东西,一直各种因素delay,今天务必要搞搞清 一.先从官方文档上尝试去解读下什么是plugin和hook 网上有现成的对你适用的插件时候,我们可以直接pip安装,拿来使用即可:但是 ...

  2. Numpy随机数(一):超几何分布

    超几何分布 产品抽样检查中经常遇到一类实际问题,假定在N件产品中有M件不合格品,即不合格率 . 在产品中随机抽n件做检查,发现k件不合格品的概率为 ,k=0,1,2,...,min{n,M}. Num ...

  3. Go语言包和文件

    工作空间 Go语言工作空间:编译工具对源码目录有严格要求,每个工作空间 (workspace) 必须由bin.pkg.src三个目录组成. src ---- 项目源码目录,里面每一个子目录,就是一个包 ...

  4. python正则表达式记录

    元字符: *  星号   它指定前一个字符可以被匹配零次或更多次 >>> re.match('a[bcd]*b', 'abcbdabcd').group() 'abcb' >& ...

  5. Flutter Navigator 跳转

    1,routes 静注册,使用 跳转 Navigator.pushNamed(context, "/main"); 2,静态跳转及销毁当前页面使用 Navigator.pushNa ...

  6. 基于两阶段提交的分布式事务实现(UP-2PC)

    引言:分布式事务是分布式数据库的基础性功能,在2017年上海MySQL嘉年华(IMG)和中国数据库大会(DTCC2018)中作者都对银联UPSQL Proxy的分布式事务做了简要介绍,受限于交流形式难 ...

  7. 用matplotlib绘制图像

    实例一: import numpy as np import matplotlib.pyplot as plt x=np.linspace(0,6,100) y=np.cos(2*np.pi*x)*n ...

  8. VUE安装步骤

    项目构建 项目推荐直接使用 Vue 官方提供的脚手架(Vue-cli),所以第一步首先是安装脚手架.在命令行或者 IDE 的 Terminal 窗口中输入以下命令即可自动安装: npm install ...

  9. ubuntu 16.04 tensorboard 学习

    一.新建tensorboard的文件夹,并在该文件夹下打开终端进入python输入以下代码 ////////新建文件夹取名tensorboard 在该目录下打开终端 import tensorflow ...

  10. (转)yum安装MariaDB(使用国内镜像快速安装,三分钟安装完毕)

    原文:https://blog.csdn.net/p__csdn/article/details/72675840 https://tinpont.com/2017/fix-yum-download- ...