Look, brother, Alex. Video mentions a job: calculate string "1-2 * ((60-30 + ( -40/5) * (9-2*5/3 + 7/3*99/4*2998 +10 * 568/14))-( -4*3)/(16-3*2))" () Not available Eval
I tried, the idea might be a little bit more complicated, but the code is not very complicated, just for reference.
Import Redef get_parentheses (s): s = S.replace (",") #空格去掉 #print (s) #print ("====================") while true:l = Re.findall ("\ ([+\-\*/\d\.] +\) ", s) #找到所有最内层的括号if l:for i in l:tmp = I.strip (' () ') result = Get_multiplicative_division (tmp) s = s.replace (I,result) s = S.replace ('-+-', '-') s = s.replace ('---', ' + ') #print (s) #print ("====================") else:s = Get_multiplicative_ Division (s) breakreturn S "" "get_multiplicative_division function is used to calculate the expression without parentheses, the realization of the idea should be able to understand" "" Def Get_multiplicative_ Division (s): Num_list = Re.findall (' [\-]?[ \d\.] + ', s) sign_list = Re.findall (' [+\*/] ', s) for I, S in Enumerate (num_list): If '-' in S and I >0 and Len (sign_list) <len ( num_list) -1:sign_list.insert (i-1, ' + ') for I, S in Enumerate (sign_list): if s = = ' * ': num_list[i+1] = float (num_list[i]) * F Loat (num_list[i+1]) num_list[i] = 0elif s = = '/': num_list[i+1] = float (num_list[i])/float (num_list[i+1]) num_list[i] = 0e Lse:continueresult = 0for I in Num_list:result + = float (i) return str (result) if __name__ = = ' __main ': s = "1-2 * ((60-30 + ( -40/5) * (9-2*5/3 + 7/3*99/4*2998 +10 * 568/14))-( -4*3)/(16-3*2)) "Print (get_parentheses (s))
In fact, the individual feel that the way to achieve a lot, just realize different ideas.
Python Implementation String Calculator