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:[email protected]
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.程序执行输出