# !/usr/bin/env python3
# _*_coding:utf-8_*_
'''
实现模拟计算器的功能:
公式: - * ( (- +(-/) * (-*/ + /*/* + * / )) - (-*)/ (-*) )
思路:
括号的计算优先级最高,应该优先计算括号内的式子,然后将值代替会原式子,循环,接着做惩处运算,最后是加减运算,然后弹出结果,
# print(eval('1-2*((60-30+(-40/5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))'))
'''
import re symbol = ['', '', '', '', '', '', '', '', '', '', '-', '+', '*', '/', '(', ')'] def check(formula):
'''
检查输入的公式的正确性:
除了十个数字和六个符号,其他的一律判错,但是这样会限制运算规则,目前先是这样规划
:param formula:
:return:
'''
symbol_flag = True
formula = re.sub(r'\s*', '', formula)
cal_list = list(formula)
for item in cal_list:
if item not in symbol:
symbol_flag = False
if not symbol_flag:
return
else:
return formula def change(formula):
'''
替换出现两个运算符在一起的情况:
:param formula:
:return:
'''
formula = formula.replace('--', '+')
formula = formula.replace('++', '+')
formula = formula.replace('**', '*')
formula = formula.replace('//', '=')
formula = formula.replace('*+', '*')
formula = formula.replace('/+', '/')
return formula def chengchu(arg):
val = arg[]
match = re.search(r'\d+\.*\d*[\*\/]+[\+\-]?\d+\.*\d*', val)
if not match:
return content = re.search(r'\d+\.*\d*[\*\/]+[\+\-]?\d+\.*\d*', val).group()
if len(content.split('*')) > :
n1, n2 = content.split('*')
value = float(n1) * float(n2)
else:
n1, n2 = content.split('/')
value = float(n1) / float(n2) before, after = re.split(r'\d+\.*\d*[\*\/]+[\+\-]?\d+\.*\d*', val, )
new_str = '%s%s%s' % (before, value, after)
arg[] = new_str
print(arg)
chengchu(arg) def jiajian(arg):
while True:
if arg[].__contains__('+-') or arg[].__contains__("++") or arg[].__contains__('-+') or arg[].__contains__(
"--"):
arg[] = arg[].replace('++', '+')
arg[] = arg[].replace('+-', '-')
arg[] = arg[].replace('--', '+')
arg[] = arg[].replace('-+', '-')
else:
break if arg[].startswith('-'):
arg[] +=
arg[] = arg[].replace('-', '&')
arg[] = arg[].replace('+', '-')
arg[] = arg[].replace('&', '+')
arg[] = arg[][:] val = arg[] match = re.search(r'\d+\.?\d*[-+]{1}\d+\.?\d*', val)
if not match:
return content = re.search(r'\d+\.?\d*[-+]{1}\d+\.?\d*', val).group() if len(content.split('+')) > :
n1, n2 = content.split('+')
value = float(n1) + float(n2)
else:
n1, n2 = content.split('-')
value = float(n1) - float(n2) before, after = re.split(r'\d+\.?\d*[-+]{1}\d+\.?\d*', val, )
new_str = '%s%s%s' % (before, value, after)
arg[] = new_str
jiajian(arg) def compute(formula):
'''
操作加减乘除:根据操作
:param formula:
:return:
'''
inp = [formula, ] #
chengchu(inp)
jiajian(inp)
if divmod(inp[], )[] == :
result = float(inp[])
result = float(result) * -
else:
result = float(inp[])
return result def calcultor(formula):
'''
递归处理括号,并计算括号内的式子,将结果返回做替换,
:param formula:
:return:
'''
# 没有括号了
if not re.search(r'\(([-+*/]*\d+\.*\d*){2,}\)', formula):
final = compute(formula)
return final
# 取出其中的一个括号,然后计算
content = re.search(r'\(([-+*/]*\d\.*\d*){2,}\)', formula).group()
# 分裂表达式
before, nothing, after = re.split(r'\(([-+*/]*\d+\.*\d*){2,}\)', formula, )
# 计算括号里的内容
content = content[:len(content) - ]
ret = compute(content)
# 计算完后然后拿到结果,然后重新拼接成一个新的式子
formula = '%s%s%s' % (before, ret, after)
return calcultor(formula) # s='1-2*((60-30+(-40/5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))'
# calcultor(s) def main():
print('欢迎使用计算器'.center(, '#'))
while True:
formula = input('计算式>>:').strip()
if formula == 'q':
exit()
elif len(formula) == :
continue
else:
formula=check(formula)
if formula == :
continue
else:
result = calcultor(formula)
print('计算结果为:\033[1;31;1m %s\033[0m' % (result))
try:
print('正确答案是:\033[1;31;1m %s\033[0m' %(eval(formula)))
except:
print('无法计算') if __name__ == '__main__':
main()

作业五:RE 模块模拟计算器的更多相关文章

  1. python作业模拟计算器开发(第五周)

    作业需求: 模拟计算器开发: 实现加减乘除及拓号优先级解析 用户输入 1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/1 ...

  2. nodejs爬虫笔记(五)---利用nightmare模拟点击下一页

    目标 以腾讯滚动新闻为例,利用nightmare模拟点击下一页,爬取所有页面的信息.首先得感谢node社区godghdai的帮助,开始接触不太熟悉nightmare,感觉很高大上,自己写代码的时候问题 ...

  3. C#基础第三天-作业答案-集合-冒泡排序-模拟名片

    .冒泡排序 Console.WriteLine("对集合里的数进行排序,请输入第一个数:"); int a = int.Parse(Console.ReadLine()); Con ...

  4. 烟大 Contest1024 - 《挑战编程》第一章:入门 Problem D: LC-Display(模拟计算器显示数字)

    Problem D: LC-Display Time Limit: 1 Sec  Memory Limit: 64 MBSubmit: 14  Solved: 3[Submit][Status][We ...

  5. 基于visual Studio2013解决C语言竞赛题之1088模拟计算器

        题目 解决代码及点评 /************************************************************************/ /* ...

  6. python爬虫主要就是五个模块:爬虫启动入口模块,URL管理器存放已经爬虫的URL和待爬虫URL列表,html下载器,html解析器,html输出器 同时可以掌握到urllib2的使用、bs4(BeautifulSoup)页面解析器、re正则表达式、urlparse、python基础知识回顾(set集合操作)等相关内容。

    本次python爬虫百步百科,里面详细分析了爬虫的步骤,对每一步代码都有详细的注释说明,可通过本案例掌握python爬虫的特点: 1.爬虫调度入口(crawler_main.py) # coding: ...

  7. jQuery系列:五个模块总结

    Query插件,以备并希望在前端方面有所长进.请批评指正. 一,类型判断全解 JQuery判断类型扩展方法:$.type() /*type: function( obj ) { if ( obj == ...

  8. Python 第五天 递归,计算器(2)

    利用函数编写如下数列: 斐波那契数列指的是这样一个数列 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377,610,987,1597,2584, ...

  9. 从零开始学Python04作业源码:模拟ATM电子银行(仅供参考)

    bin目录:程序启动入口 ATM_start.py: #!/usr/bin/python # -*- coding: utf-8 -*- # 模拟ATM电子银行+登录账户权限控制+管理员管理模块 # ...

随机推荐

  1. java map遍历、排序,根据value获取key

    Map 四种遍历: Map<String,String> map = new HashMap<String, String>(); map.put("one" ...

  2. Windows Live Writer介绍及相关问题解决

    今天本来想说更新一篇我的文章,更新的过程中添加了很多的内容,里面的图片太多了,导致我浏览器占用的内存不断增大,浏览器变得很卡,最后过了好久我终于更新完文章打算保存的时候居然卡住,然后所有我更新的文字和 ...

  3. python中的return的返回与执行

    author:headsen  chen date:2018-03-21  15:12:09 notice:created by  headsen chen himself  and not allo ...

  4. 标准mysql(x64) Windows版安装过程

    mysql x64不提供安装器,不提供安装器,不提供安装器-- 每次查英文文档有点慢,不够简. 5.7.6以后的64位zip包下载后解压是没有data目录的. 进入解压后的bin目录:(我用的powe ...

  5. Microsoft AI - Custom Vision

    概述 前几天的 Windows Developer Day 正式发布了 Windows AI Platform,而作为 Windows AI Platform 的模型定义和训练,更多还是需要借助云端来 ...

  6. 利用Java生成UUID

    UUID是什么? UUID 是 通用唯一识别码(Universally Unique Identifier)的缩写,是一种软件建构的标准,亦为开放软件基金会组织在分布式计算环境领域的一部分.其目的,是 ...

  7. 在oracle中,group by后将字符拼接,以及自定义排序

    1.在oracle中,group by后将字符拼接.任务:在学生表中,有studentid和subject两个字段.要求对studentid进行group by分组,并将所选科目拼接在一起.oracl ...

  8. 笔记:Eclipse 安装 Hibernate Tools

    在线安装,要求 Eclipse Neon 4.6 版本和Java 8,在 Help > Install New Software,在打开的窗体中的 Work with 中输入URL地址" ...

  9. poj-1503-java大数相加

    Description One of the first users of BIT's new supercomputer was Chip Diller. He extended his explo ...

  10. Be Better , Be Better

    Be Better! 这不是一道题,只是我的flag.初三寒假,一个本应该对着计算机翻天覆雨的假期,我在鬼班撸高中课...其实感触是从初中课得来的.有些事,以前我说是我不懂,现在我不说不是我不懂.Ju ...