標籤:結果 特殊 __name__ group 符號 計算 span 操作 算數
#!/bin/env python# -*- coding:utf-8 -*-‘‘‘實現能計算類似1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2))公式‘‘‘import rea =r‘1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 ))- (-4*3)/(16-3*2))‘# */運算函數def chengchu(str): calc = re.split("[*/]",str) #用*/分割公式 OP = re.findall("[*/]",str) #找出所有*和/號 ret = None for index,i in enumerate(calc): if ret: if OP[index-1] == "*": ret *= float(i) elif OP[index-1] == "/": ret /= float(i) else: ret = float(i) return ret# 去掉重複運算,和處理特列+-符號def del_double(str): str = str.replace("++", "+") str = str.replace("--", "-") str = str.replace("+-","-") str = str.replace("- -","-") str = str.replace("+ +","+") return str# 計算主控制函數def calc_contrl(str): tag = False str = str.strip("()") # 去掉最外面的括弧 str = del_double(str) # 調用函數處理重複運算 find_ = re.findall("[+-]",str) # 擷取所有+- 操作符 split_ = re.split("[+-]",str) #正則處理 以+-操作符進行分割,分割後 只剩*/運算子 if len(split_[0].strip()) == 0: # 特殊處理 split_[1] = find_[0] + split_[1] # 處理第一個數字前有“-”的情況,得到新的帶符號的數字 # 處理第一個數字前為負數“-",時的情況,可能後面的操作符為“-”則進行標記 if len(split_) == 3 and len(find_) ==2: tag =True del split_[0] # 刪除原分割數字 del find_[0] else: del split_[0] # 刪除原分割數字 del find_[0] # 刪除原分割運算子 for index, i in enumerate(split_): # 去除以*或/結尾的運算數字 if i.endswith("* ") or i.endswith("/ "): split_[index] = split_[index] + find_[index] + split_[index+1] del split_[index+1] del find_[index] for index, i in enumerate(split_): if re.search("[*/]",i): # 先計算含*/的公式 sub_res = chengchu(i) #調用剩除函數 split_[index] = sub_res # 再計算加減 res = None for index, i in enumerate(split_): if res: if find_[index-1] == "+": res += float(i) elif find_[index-1] == "-": # 如果是兩個負數相減則將其相加,否則相減 if tag == True: res += float(i) else: res -= float(i) else: # 處理沒有括弧時會出現i 為空白的情況 if i != "": res = float(i) return resif __name__ == ‘__main__‘: while True: calc_input = input("請輸入計算公式\n預設為:%s:" %a).strip() try: if len(calc_input) ==0: calc_input = a calc_input = r‘%s‘%calc_input # 做特殊處理,保持字元原形 flag = True # 初始化標誌位 result = None # 初始化計算結果 # 迴圈處理去括弧 while flag: inner = re.search("\([^()]*\)", calc_input)# 先擷取最裡層括弧內的單一內容 #print(inner.group()) # 有括弧時計算 if inner: ret = calc_contrl(inner.group()) # 調用計算控制函數 calc_input = calc_input.replace(inner.group(), str(ret)) # 將運算結果,替換原處理索引值處對應的字串 print("處理括弧內的運算[%s]結果是:%s" % (inner.group(),str(ret))) #flag = True # 沒有括弧時計算 else: ret = calc_contrl(calc_input) print("\033[0;31m最終計算結果為:%s\033[0m"% ret) print("\033[0;32meval計算結果:%s\033[0m"% eval(calc_input)) #結束計算標誌 flag = False except: print("你輸入的公式有誤請重新輸入!")
python練習---類比計算機