#!/usr/bin/env python# Coding:utf-8Import Redef Dealwith (Express): Express.replace ('+-','-') Express.replace ('--','+') returnexpressdef Col_suanshu (exp):if '/' inchexp:a,b= Exp.split ('/') returnStrfloat(a)/float(b))if '*' inchexp:a,b= Exp.split ('*') returnStrfloat(a) *float(b) def get_no_barcate (Express): Express=express.strip ('()') Print ('>>>', Express) whileTrue:ret= Re.search ("-?\d+\.? \d*[*/]-?\d+\.? \d*", Express)ifRet:res=Col_suanshu (Ret.group ()) Express= Express.replace (Ret.group (),'+'+res) print ('An expression', Express) Express=Dealwith (Express)Else: Ret= Re.findall ('-?\d+\.? \d*', Express) sum=0 forIinchRet:sum+=float(i)returnstr (SUM) Express='1-2* ((60-30 + ( -40/5) * (9-2*5/3 +7/3*99/4*2998 +10 *568/14))-( -4*3)/(16-3*2))'new_express= Express.replace (' ',"') print (new_express) print ('the correct result of the Operation', eval (new_express)) whileTrue:ret= Re.search ('\([^()]+\)', new_express) # Print (Ret.group ()) #print (Ret.group ())ifRet:barcate_sum=get_no_barcate (Ret.group ()) Print ('return value', barcate_sum) new_express=New_express.replace (Ret.group (), barcate_sum) new_express=Dealwith (new_express)Else: Sum=get_no_barcate (new_express) print (sum) Break
Using regular expressions to implement the Operation Express = ' 1-2* ((60-30 + ( -40/5) * (9-2*5/3 +7/3*99/4*2998 +10 *568/14))-( -4*3)/(16-3*2)) '