import re def chen_chu(str): res = re.search("[^()]+",str) res_l = re.split("[*/]",res.group()) res_f_l = re.findall("[*/]",res.group()) n = None for ... ...
import re def chen_chu(str): res = re.search("[^()]+",str) res_l = re.split("[*/]",res.group()) res_f_l = re.findall("[*/]",res.group()) n = None for i in range(len(res_l)): if n: if res_f_l[i-1] == "*": n *= int(res_l[i]) elif res_f_l[i-1] == "/": n /= int(res_l[i]) else: n = int(res_l[i]) return int(n) def add_sub(str): res = re.search("[^()]+",str) res_l = re.split("[-+]",res.group()) res_f_l = re.findall("[-+]",res.group()) if re.match("[-+]",res.group()): if res_f_l[0] == "-": res_l[1] = -int(res_l[1]) res_l = res_l[1:] res_f_l = res_f_l[1:] if len(res_f_l) == 0: return res_l[0] n = None for i in range(len(res_l)): if n: if res_f_l[i-1] == "+": n += int(res_l[i]) elif res_f_l[i-1] == "-": n -= int(res_l[i]) else: n = int(res_l[i]) return int(n) def ts(ret): new_ret = [] for index,item in enumerate(ret): if item.endswith("*") or item.endswith("/"): new_ret.append("%s-%s" %(ret[index],ret[index+1])) elif re.search("[*/]",ret[index]): new_ret.append(ret[index]) return new_ret if __name__ == "__main__": # a = "2+(3*(2+2-6)+5*3)" a = input("清輸入計算公式:") a = a.replace(" ","") count = 2 while True and count > 0: ret = re.search(r"\([^()]+\)",a) if ret: ret_v = ret.group() else: count -= 1 ret_v = a if "+" in ret_v or "-" in ret_v: if "*" in ret_v or "/" in ret_v: res = re.findall("[^()]+",ret_v) res_l = re.split(r"[-+]",res[0]) res_l = ts(res_l) for item in res_l: res_l_v = chen_chu(item) a = a.replace(item,str(res_l_v)) a =a.replace("+-","-") a = a.replace("--","+") else: res_l_v = add_sub(ret_v) a = a.replace(ret_v, str(res_l_v)) a = a.replace("+-", "-") a = a.replace("--", "+") else: if "*" in ret_v or "/" in ret_v: res_l_v = chen_chu(ret_v) a = a.replace(ret_v, str(res_l_v)) a = a.replace("+-", "-") a = a.replace("--", "+") print(a)