7_python之路之python计算器

1.程序说明:Readme.cmd

1.程序文件及说明:
calculator.py 2.python版本:python-3.5.3 3.程序使用:python calculator.py "1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )"
【使用双引号引住需要运算的内容】 4.程序功能解析:
计算器 5.程序执行结果:请亲自动手执行或者查看我的博客 6.程序博客地址:http://www.cnblogs.com/chenjw-note/p/8523839.html

2.程序代码:calculator.py

#!/usr/bin/env python
# _*_ coding: utf-8 _*_
# author:chenjianwen
# email:1071179133@qq.com
import re
import sys ##计算乘除法
def compute_mutiply_and_dividend(formula):
operators = re.findall(r'[*/]',formula)
calc_list = re.split('[*/]',formula)
calc_res = None
for index,i in enumerate(calc_list):
if calc_res:
if operators[index - 1] == "*":
calc_res *= float(i)
elif operators[index - 1] == "/":
calc_res /= float(i)
else:
calc_res = float(i)
return calc_res ##计算加减
def compute_add_and_subt(formula):
operators = re.findall(r'[+-]',formula)
calc_list = re.split(r'[+-]',formula)
calc_res = None
for index,i in enumerate(calc_list):
if calc_res:
if operators[index - 1] == "+":
calc_res += float(i)
elif operators[index - 1] == "-":
calc_res -= float(i)
else:
calc_res = float(i)
return calc_res ##消除两个符号
def remove(formula):
formula = formula.replace("+-","-")
formula = formula.replace("-+", "-")
formula = formula.replace("++", "+")
formula = formula.replace("--", "-")
formula = formula.replace("- -", "+")
return formula ##处理特殊情况1 - 2 * -14969036.7968254 ['-', '-'] ['1 ', ' 2 * ', '14969036.7968254'] ' 2 * '
def special_done(a,b):
for index,i in enumerate(b):
i = i.strip()
if i.endswith("*") or i.endswith("/"):
b[index] = b[index] + a[index] + b[index + 1]
del b[index + 1]
del a[index]
return a,b #具体运算
def compute(formula):
#print(formula)
formula = formula.strip('()')
a = re.findall(r'[+-]',formula)
b = re.split(r'[+-]',formula)
if len(b[0].strip()) == 0: ##判断如果第一个是减号,值为空了无法运算,将其减号赋下一个值
b[1] = a[0] + b[1]
del a[0]
del b[0]
#print(a)
#print(b)
a,b = special_done(a,b)
for index,i in enumerate(b):
if re.search(r'[*/]',i):
res = compute_mutiply_and_dividend(i)
b[index] = res
#print(b)
##开始运算+ -
total_res = None
for index,i in enumerate(b):
if total_res:
if a[index - 1] == "+":
total_res += float(i)
elif a[index - 1] == "-":
total_res -= float(i)
else:
total_res = float(i)
#print("\033[32;1m[%s]运算结果:\033[0m" % formula, total_res)
return total_res #主逻辑
def calc(formula):
calc_status = True
calc_res = None
while calc_status:
m = re.search(r'\([^()]*\)',formula)
if m:
sub_res = compute(m.group())
formula = formula.replace(m.group(),str(sub_res))
formula = remove(formula)
#print(formula)
else:
#print('\033[41;1m----没拓号了...---\033[0m') print('\n\n\033[42;1m最终结果:\033[0m', compute(formula))
calc_status = False
print("计算结束") calc(sys.argv[1])
print("eval的计算结果:",eval(sys.argv[1]))

3.程序执行输出

7_python之路之python计算器的更多相关文章

  1. Python之路,Day6 - Python基础6

    本节大纲: 模块介绍 time &datetime模块 random os sys shutil json & picle shelve xml处理 yaml处理 configpars ...

  2. python 计算器的(正则匹配+递归)

    经过2天的长时间的战斗,python计算器终于完成了. import re val="1-2*((60-30*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3 ...

  3. Python之路,Day4 - Python基础4 (new版)

    Python之路,Day4 - Python基础4 (new版)   本节内容 迭代器&生成器 装饰器 Json & pickle 数据序列化 软件目录结构规范 作业:ATM项目开发 ...

  4. python开发之路:python数据类型(老王版)

    python开发之路:python数据类型 你辞职当了某类似微博的社交网站的底层python开发主管,官还算高. 一次老板让你编写一个登陆的程序.咔嚓,编出来了.执行一看,我的妈,报错? 这次你又让媳 ...

  5. Python计算器实操

    要求: 开发一个简单的python计算器 实现加减乘除及拓号优先级解析 用户输入 1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * ...

  6. 作业1开发一个简单的python计算器

    开发一个简单的python计算器 实现加减乘除及拓号优先级解析 用户输入 1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568 ...

  7. 老男孩python作业5-开发一个简单的python计算器

    开发一个简单的python计算器 实现加减乘除及拓号优先级解析 用户输入 1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568 ...

  8. (路-莫)-Python基础一

    一,Python介绍 1,python的出生与应用 python的创始人为吉多·范罗苏姆(Guido van Rossum).1989年的圣诞节期间,吉多·范罗苏姆(中文名字:龟叔)为了在阿姆斯特丹打 ...

  9. Python菜鸟之路:Python基础-线程、进程、协程

    上节内容,简单的介绍了线程和进程,并且介绍了Python中的GIL机制.本节详细介绍线程.进程以及协程的概念及实现. 线程 基本使用 方法1: 创建一个threading.Thread对象,在它的初始 ...

随机推荐

  1. redis高可用 - Master&Slave

    Master&Slave也就是我们所说的主从复制,即主机数据更新后根据配置和策略,自动同步到备机的机制.其中Master以写为主,Slave以读为主. Master&Slave的作用主 ...

  2. [原][译][osgearth]关于Features & Symbology (特征与符号)(OE绘制矢量几何与特殊字符)讲解(OE官方文档翻译)

    原文参考:http://docs.osgearth.org/en/latest/user/features.html 自己翻译的,本人英文水平有限,有问题看原链接,原文 20170802重置修改部分翻 ...

  3. Oracle10g客户端链接服务端配置

    Oracle10g客户端工具plsql链接服务端配置 Oracle10g客户端工具比如plsql,在网络中链接服务端问题比较多中国菜刀,经常出现很多莫名其妙的问题.实际上不是plsql的配置,问题还是 ...

  4. SSM(Spring+SpringMVC+Mybatis)+Mysql 框架整合搭建流程以及其间注意事项

    复习SSM框架,太久没用自己手动撘一个,发现自己还是有很多地方忘记了和没注意的事项... 首先,直接给出总流程: 零.引jar包 1.引包(或者写maven.pom) 一.数据库部分 设计数据库各表结 ...

  5. web 移动端事件总结

    1.https://www.jianshu.com/p/6f85e957a725 (web 移动端事件总结)

  6. 手写DCGAN

    //加上了注释,对pytorch又加深了理解import torch as t from torch import nn from torch.autograd import Variable fro ...

  7. [转载]字符串匹配的KMP算法

    作者: 阮一峰 日期: 2013年5月 1日 字符串匹配是计算机的基本任务之一. 举例来说,有一个字符串"BBC ABCDAB ABCDABCDABDE",我想知道,里面是否包含另 ...

  8. PHP:第五章——字符串的统计及查找

    <?php header("Content-Type:text/html;charset=utf-8"); /*字符串的统计与查找*/ //1.获取字符串的长度 //1)st ...

  9. C语言对表达式的求值顺序不是明确规定的

    讨论区看到的 WA来自那些递归下降求解的代码. 第一种情况,使用|| 和 &&: 例如s为所给串 int getval() { switch(s[c_s++]) { case 'p': ...

  10. HP-UX 下用户被锁

    /usr/lbin/getprpw -m lockout root 如果返回lockout=0000000 该帐号是非锁定的,如果是其它的如:lockout=0001000则表示该帐号被锁定 如果是测 ...