import re
from functools import reduce # 定义一个只计算两个数的乘法或除法的函数:
def multiply_division(exp):
if "*" in exp:
# first=exp.split("*")[0]
# second=exp.split("*")[1]
first,second=exp.split("*")
return float(first)*float(second)
if "/" in exp:
first,second=exp.split("/")
return float(first) / float(second) # 定义一个只计算两个数的加法或减法的函数:
def add_sub(exp):
if "-" in exp:
# first=exp.split("*")[0]
# second=exp.split("*")[1]
first,second=exp.split("-")
return float(first)-float(second)
if "/" in exp:
first,second=exp.split("+")
return float(first) + float(second) # 对于加减法要处理正负号 while循环处理所有的正负号
def exp_fmt(exp):
while re.search('[+-]{2,}',exp): # 循环终止条件是re.search(pattern)为空
exp = exp.replace('--','+')
exp = exp.replace('+-','-')
exp = exp.replace('-+','-')
exp = exp.replace('++','+')
return exp # ret=multiply_division("-1/4")
# print(ret)
# ret=add_sub("1-4")
# print(ret) def multiply_division_replace(exp):
# exp=exp_fmt(exp)
while True:
ret = re.search('\d+(\.\d+)?[*/][+-]?\d+(\.\d+)?', exp)
# ret = re.search('\d+(\.\d+)?[*/]-?\d+(\.\d+)?', exp)
if ret:
res=multiply_division(ret.group(0))
exp=exp.replace(ret.group(0),str(res))
else:
break
return exp # def add_sub_replace(exp):
# while True:
# exp = exp_fmt(exp)
# ret = re.search('\d+(\.\d+)?[+-]\d+(\.\d+)?', exp)
# print(ret.group(0))
# if ret:
# res=add_sub(ret.group(0))
# exp=exp.replace(ret.group(0),str(res))
# else:
# break
# return exp
#
# exp="1—5+2+3" --> -4+2+3 负号没法处理 最终报错
# exp=add_sub_replace(exp)
# print(exp) def remove_addsub(exp):
print(exp)
ret = re.findall('[-+]?\d+(?:\.\d+)?',exp) # (?:\.\d+)
# (?:\.\d+)? 表示一个匹配不用保存的分组,要不然,findall返回的将是括号内的值的列表。
print(ret)
res = reduce(lambda a,b:float(a)+float(b),ret) # 聚合求ret列表内的所有元素的和
return res
# count = 0
# for i in ret:
# count += float(i)
# print(count) exp="1--3*+5/-5+2+3"
# exp="1—5+2+3" --> -4+2+3 负号没法处理
exp=multiply_division_replace(exp)
# exp=add_sub_replace(exp)
print(exp)
老师答案

import re
from functools import reduce def mul_div(exp): # 计算两个数的乘法或者除法
if '*' in exp:
a, b = exp.split('*')
return float(a)*float(b)
if '/' in exp:
a, b = exp.split('/')
return float(a) / float(b) def exp_fmt(exp):
while re.search('[+-]{2,}',exp):
exp = exp.replace('--','+')
exp = exp.replace('+-','-')
exp = exp.replace('-+','-')
exp = exp.replace('++','+')
return exp def remove_addsub(exp):
ret = re.findall('[-+]?\d+(?:\.\d+)?',exp)
res = reduce(lambda a,b:float(a)+float(b),ret)
return res def remove_muldiv(exp): # 计算表达式中的所有的乘除法
while True:
ret = re.search('\d+(\.\d+)?[*/]-?\d+(\.\d+)?',exp)
if ret:
son_exp = ret.group() # 3*4 12*5
res = mul_div(son_exp)
exp = exp.replace(son_exp,str(res))
else:return exp def cal(exp):
res = remove_muldiv(exp) # 计算乘除
res = exp_fmt(res) # 符号整理
ret = remove_addsub(res) # 计算加减
return ret def main(exp):
exp = exp.replace(' ','')
while True:
ret = re.search('\([^()]+\)', exp)
if ret:
res = cal(ret.group())
exp = exp.replace(ret.group(), str(res))
else: return cal(exp) exp = '1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )'
ret = main(exp)
print(ret)

python_计算器的更多相关文章

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

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

  2. 自己动手写计算器v1.1

    这个改动主要是使用工厂模式替代了简单工厂模式,这样做的好处是如果以后我们要扩充其他运算时,就不用总是去修改工厂类, 这是可以采取工厂模式,主要是将原来简单工厂类的逻辑判断分离出来,将它作为一个借口,与 ...

  3. 自己动手写计算器v1.0

    今天突发奇想,想着看了还几个设计模式了,倒不如写点东西来实践它们.发现计算器这种就比较合适,打算随着设计模式的学习,会对计算器不断的做改进. 包括功能的增加和算法的改进.初学者难免犯错,希望大家不吝指 ...

  4. 【IOS开发笔记03-视图相关】简单计算器的实现

    UIView 经过前几天的快速学习,我们初步了解的IOS开发的一些知识,中间因为拉的太急,忽略了很多基础知识点,这些知识点单独拿出来学习太过枯燥,我们在今后的项目中再逐步补齐,今天我们来学习APP视图 ...

  5. [LeetCode] Basic Calculator 基本计算器

    Implement a basic calculator to evaluate a simple expression string. The expression string may conta ...

  6. JS-自制提速小工具:开发页面时需要按比例计算宽高值的快速计算器

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

  7. 由ArcMap属性字段自增引出字段计算器使用Python的技巧

    1.前言       前些日子有人问我ArcMap中要让某个字段的值实现自增有什么方法?我首先想到像SQL Server中对于数值型字段可以设置自增.所以我打开ArcCatalog查看发现只提供默认值 ...

  8. 前端学PHP之面向对象系列第六篇——简单图形面积计算器实现

    前面的话 本文用面向对象的技术来实现一个简单的图形面积计算器 图形类 //rect.class.php <?php abstract class Shape{ public $name; abs ...

  9. tn文本分析语言(四) 实现自然语言计算器

    tn是desert和tan共同开发的一种用于匹配,转写和抽取文本的语言.解释器使用Python实现,代码不超过1000行. github地址:https://github.com/ferventdes ...

随机推荐

  1. 热力图 vue 项目中使用热力图插件 “heatmap.js”(保姆式教程)

    我现在写的这项目是用CDN引入 heatmap.js, 可根据自己项目情况使用哪种方式引入插件. 官网地址 "https://www.patrick-wied.at/static/heatm ...

  2. 《罗辑思维》试读:U盘化生存

    <罗辑思维>试读:U盘化生存 何为"U盘" 记得有一次我到一个大学去讲课,我随机做了一个调查.我说大四啦,咱们班同学谁找着工作了,一堆人举手.我又问都加入什么样的组织了 ...

  3. 多测师讲解python函数 _open_高级讲师肖sir

    open()函数 #open() 函数用于打开一个文件,创建一个 file 对象 #Python open() 函数用于打开一个文件,并返回文件对象, # 在对文件进行处理过程都需要使用到这个函数,如 ...

  4. MeteoInfoLab脚本示例:计算水平螺旋度

    尝试了用MeteoInfoLab编写计算水平螺旋度的脚本,结果未经验证.脚本程序: print 'Open data files...' f_uwnd = addfile('D:/Temp/nc/uw ...

  5. C#使用RabbitMq队列(Sample,Work,Fanout,Direct等模式的简单使用)

    1:RabbitMQ是个啥?(专业术语参考自网络) RabbitMQ是实现了高级消息队列协议(AMQP)的开源消息代理软件(亦称面向消息的中间件). RabbitMQ服务器是用Erlang语言编写的, ...

  6. 扫描仪扫描文件处理-ABBYY自动矫正图像歪斜

    修改界面语言: 设置为不识别图片文字(因为我们只需要把图片歪斜校正): 保存无损彩色格式:

  7. mysql间隙锁 转

    前面一文 mysql锁 介绍了mysql innodb存储引擎的各种锁,本文介绍一下innodb存储引擎的间隙锁,就以下问题展开讨论 1.什么是间隙锁?间隙锁是怎样产生的? 2.间隙锁有什么作用? 3 ...

  8. jquery1.9+,jquery1.10+ 为什么不支持live方法了?

    live() 替换成 on() die()  替换成off() 根据jQuery的官方描述,live方法在1.7中已经不建议使用,在1.9中删除了这个方法.并建议在以后的代码中使用on方法来替代. o ...

  9. node服务器基本搭建

    const http = require('http') // 引入http模块 http.createServer(function(req,res){ // 创建一个http服务器 // 这里是一 ...

  10. vue渐进式开发的理解和指令

    1.vue渐进式开发 vue是一个渐进式的框架,轻量,易于上手,为啥是渐进式那,我当时也很蒙,比如的官网是jquery写的,就可以通过script标签引入事先准备好的vue.min.js的压缩源代码或 ...