#!/usr/bin/env python
import re
def deal_negative_issue(calc_list):
new_calc_list=[] #定義一個新的空列表,後面篩選完成後將數據放入新列表中
for index,item in enumerate(calc_list):
if item.strip().endswith("*") or item.strip().endswith("/"): #挑選出以乘號或除號結尾的字符串
new_calc_list.append("%s-%s"%(calc_list[index],calc_list[index+1])) #拼接字符串 處理相似2*5/-3
# elif ("*" or "/") in item: #找出列表中的有乘除的選項,這種寫法我試了好像只匹配*在,單獨40/5這種匹配不出來
elif ("/") in item or ("*") in item:
print(item)
new_calc_list.append(item)
print("new_calc_ist",new_calc_list)
return new_calc_list
def deal_unusual_issue(formula):
formula = formula.replace("++","+")
formula = formula.replace("+-", "-")
formula = formula.replace("-+", "-")
formula = formula.replace("--", "+")
formula = formula.replace("- -", "+")
return formula
# def addition_and_subtraction(formula):
# sub_calc_list = re.split("[+-]",formula)
# sub_operator_list = re.findall("[+-]",formula)
# print(type(sub_calc_list), sub_operator_list)
# totle_res = None
# for index,i in enumerate(sub_calc_list):
# if totle_res: #sub_res爲真,表示這不是第一次循環
# if sub_operator_list[index-1]=="+": #經過sub_operator_list中的index判斷究竟是加法仍是減法
# totle_res += float(i)
# else:
# totle_res -= float(i)
# else:
# sub_res = float(i)
# print(totle_res)
def calculating(formula):
print("運算",formula)
calc_list = re.split("[+-]",formula) #經過+-符號將各個乘除運算分隔出來
calc_list = deal_negative_issue(calc_list)
print(calc_list)
for item in calc_list:
sub_calc_list = re.split("[*/]",item)
sub_operator_list = re.findall("[*/]",item) #將乘號除號經過列表方式分隔出來
print(sub_calc_list,sub_operator_list)
sub_res = None
for index,i in enumerate(sub_calc_list):
if sub_res: #sub_res爲真,表示這不是第一次循環
if sub_operator_list[index-1]=="*": #經過sub_operator_list中的index判斷究竟是加法仍是減法,
sub_res *= float(i)
else:
sub_res /= float(i)
else:
sub_res = float(i)
print("[%s]="%item,sub_res)
formula = formula.replace(item,str(sub_res))
formula = deal_unusual_issue(formula)
print(formula)
#計算+-法
totle_calc_list = re.split("[+-]", formula)
totle_operator_list = re.findall("[+-]", formula) # 將乘號除號經過列表方式分隔出來
print(totle_calc_list, totle_operator_list)
totle_res = None
for index,item in enumerate(totle_calc_list):
if totle_res: #sub_res爲真,表示這不是第一次循環
if totle_operator_list[index-1]=="+": #經過sub_operator_list中的index判斷究竟是加法仍是減法,
totle_res += float(item)
else:
totle_res -= float(item)
else:
totle_res = float(item)
# return formula
print("[結果]=", totle_res)
return totle_res
def calc(formula):
parentheses_flag = True
calc_res = None
while parentheses_flag:
m = re.search("\([^()]*\)",formula) #找出最底層的括號,一個一個找
print(m)
if m:
# print(type(m.group()))
subformula = m.group().strip("()") #把找出來的括號剝離
subres = calculating(subformula)
formula = formula.replace(m.group(),str(subres))
else:
print("沒括號了")
print("最終結果爲",calculating(formula))
parentheses_flag = False
if __name__ == '__main__':
res = calc("1 - 2 * ( (60-30 +(9-2*5/-3 + 7 /3*99/4*2998 +10 * 568/14 ) * (40/5)) - (4*3)/ (16-3*2) )")
#res = calc("2 * (40/5)")python
#備註:-40/5功能沒有實現app