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. 上海仪电Azure Stack技术深入浅出系列2:Azure Stack与Azure的有QoS保证的网络联通实现方法和对比测试

    本篇文章作为<Azure Stack技术深入浅出系列>的第二篇,将描述我们目前在构建基于Azure Stack混合云业务解决方案方面所面临的网络连通困难,以及相关技术人员为解决这一问题所做 ...

  2. Sum Problem

    2018-04-22 19:59:52 Sum系列的问题是Leetcode上的一个很经典的系列题,这里做一个简单的总结. 167. Two Sum II - Input array is sorted ...

  3. 【Demo】CSS3 动画 加载进度条

    实例结果图: 完整代码: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> ...

  4. 动态创建OATipBean

    动态创建OATipBean. 动态创建的OATipBean无法直接设置提示内容,需要添加一个静态文本. 参考User Guide示例如下. If you need to create a tip pr ...

  5. db2时间函数

    获取当前日期: select current date from sysibm.sysdummy1; values current date; --获取当前时间 select current time ...

  6. EPANET头文件解读系列6——HASH.H

    该文件是EPANET中HASH.C的头文件,下面列出了该文件的源码以及我的中文注释 /* HASH.H**** Header file for Hash Table module HASH.C***/ ...

  7. Django中CSS加载background url('')问题

    Django中CSS加载background url('')问题   在django中, 默认CSS中如果有 background url('images/a.jpg') 这类的属性,会被django ...

  8. RALL资源获取初始化,删除器

    body, table{font-family: 微软雅黑; font-size: 10pt} table{border-collapse: collapse; border: solid gray; ...

  9. vue.js 源代码学习笔记 ----- codegenEvents.js

    /* @flow */ const fnExpRE = /^\s*([\w$_]+|\([^)]*?\))\s*=>|^function\s*\(/ const simplePathRE = / ...

  10. ASP.NET FORM认证配置排错记录

    搞了2小时都不能实现自动跳转到登录页面,后删除了配置文件中的name,就解决问题了. <authorization>      <deny users="?" / ...