Exercise-expression calculation (multi-layer brackets, adding, subtraction, multiplication, division, division, remainder, and power), multiple layers

Source: Internet
Author: User

Exercise-expression calculation (multi-layer brackets, adding, subtraction, multiplication, division, division, remainder, and power), multiple layers

Import re # computation dictionary calc = {'+': lambda x, y: x + y, # Add '-': lambda x, y: x-y, # subtract '*': lambda x, y: x * y, # multiply by '/': lambda x, y: x/y, # Remove '%': lambda x, y: x % y, # Take the remainder '//': lambda x, y: x // y, # Remove '^': lambda x, y: x ** y # Power (I don't know if it is a bug, but the results are different in different ways. The following is an example)} # determine the priority function def order (lis = []): # if the list starts with '-', the first number is negative. if lis [0] = '-': lis. pop (0) lis [0] =-float (lis [0]) while len (lis )! = 1: # continue to execute for I in range (len (lis) if the final result is not obtained: # determine whether the operator muldiv = re. search (R' [\ ^ */% +-]/? $ ', Str (lis [I]) if muldiv: # judge whether to add or not, subtract if re. search (R' [+-] ', str (lis [I]): # determine whether there is a higher priority power in the future, multiplication, division, remainder, and division operation if re. search (R' [\ ^ */%]/? ', Str (lis): continue # determines whether the current operation is multiplication, division, division, and division. elif re. search (R' [*/%]/? ', Str (lis [I]): # determine whether there is a higher priority power operation in the future if re. search (R' [\ ^] ', str (lis): continue num1 = float (lis [I-1]) # parameter 1 # if I is a symbol, '-' is displayed, indicating that the number is negative. if lis [I + 1] = '-': lis. pop (I + 1) lis [I + 1] =-float (lis [I + 1]) num2 = float (lis [I + 1]) # Take parameter 2 result = calc [muldiv. group ()] (num1, num2) # Calculate by operator for m in range (2): # Delete the calculated expression lis. pop (I) lis [I-1] = result # Add the result to the expression break # Return and start again, because the index location has changed, it is not suitable to continue with the value r Eturn lis # Main Function def operation (exp): # unified format expression exp = exp. replace ('',''). replace (') (', ') * (') exp = exp. replace ('++', '+ '). replace ('--', '+') exp = exp. replace ('+ -','-'). replace ('-+', '-') exp = exp. replace ('**', '^') # use the regular expression to split the string exp = re. findall (R' \ d + (?: \. \ D + )? | [\ D +]/? ', Exp) while' ('in exp: # judge whether there are any parentheses # Use loops to find matching parentheses, after the expression in parentheses is executed, the loop for I in range (len (exp): if exp [I] = '(': if I> 0 and re. search (R' \ d + (?: \. \ D + )? ', Str (exp [I-1]): exp. insert (I, '*') # change the format similar to 2 () to 2 *() form break start = I # record the last "(" location elif exp [I] = ')': fir = exp [: start] # mid = exp [start + 1: I] # Intermediate List of slices to be calculated end = exp [I + 1:] # mid = order (mid) # determine the priority calculation to obtain the calculation result exp = fir + mid + end # After calculating the expressions in parentheses, print (str (exp ). replace (',',''). replace ("'", '') break # jumps out of the for Loop and no longer calculates the next set of parentheses (because the original list has changed and the index has changed, it is not suitable for the next value) else: # Without parentheses, directly execute the calculation order (exp) return float (exp [0]) if _ name _ = '_ main __': l = "-2.5*(3.562 ** 2 + 5 *-60 //-2) * (3 *-5/6-9%-10 // 3 )) "# decomposition steps are as follows #-2.5*(162.68784399999998*(3 *-5/6-9%-10/3) #-2.5*(162.68784399999998 *-1.5) #-2.5 *-244.03176599999998 #610.0794149999999 ret = operation (l) print ('built-in function: % s' % eval (l) print ('write function: % s' % ret) # It is also a power operation, but the result is not the same num1 =-3.562 num2 = 8 print ('eval: % F number: % F variable: % f pow: % F' % (eval ('-3.562 ** 8'),-3.562 ** 8, num1 ** num2, pow (-3.562, 8 )))

  

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.