Python calculator (Day 4), python Calculator

Source: Internet
Author: User

Python calculator (Day 4), python Calculator

Job:

Use regular expressions and recursion to implement the calculator function.

 

Implementation:

1. Implement calculation with parentheses

2. Implement functions such as exponential, addition, subtraction, multiplication, division, and remainder

I. instance description:

This instance has written a version by itself, but there is still a bug, for example,-2-2 and other computing problems. Therefore, in addition to the code of Wu SIR, the function such as index and remainder is added.

Idea Of This calculator:
1. Recursively search for expressions that only contain numbers and operators and calculate the results
2. Since decimal places are ignored in integer calculation, all numbers are considered floating-point operations to retain decimal places.
Technology used:
1. Regular Expression
2. Recursion

 

Ii. flowchart:

#! /Usr/bin/python27 # _ * _ coding = UTF-8 _ * _ '''created on August 1 @ author: Wang kai''' ''' This calculator concept: 1. recursive search expression contains only numbers and operators. Calculation Result 2. Since integer calculation ignores decimal places, all numbers are considered floating-point operations, to retain decimal use technology: 1. Regular Expression 2. Recursive Execution process is as follows: * ****************** calculate the expression: 1-2*(60-30 + (-40.0/5) * (9-2*5/3 + 7/3*99/4*2998 + 10*568/14)-(-4*3)/(16-3*2 )) * ****************** before: ['1-2*(60-30 + (-40.0/5) * (9-2*5/3 + 7/3*99/4*2998 + 10*568/14)-(-4*3)/(16-3 * 2) ']-40.0/5 =-8.0 after: ['1-2*(60-30 +-8.0*(9-2*5/3 + 7/3*99/4*2998 + 10*568/14)-(-4*3) /(16-3*2) '] =========== last computing end ========== before: ['1-2*(60-30 +-8.0*(9-2*5/3 + 7/3*99/4*2998 + 10*568/14)-(-4*3) /(16-3*2) '] 9-2*5/3 + 7/3*99/4*2998 + 10*568/14 = 173545.880953 after: ['1-2*(60-30 +-8.0*173545.880953)-(-4*3)/(16-3*2 )) '] ========== last computing end ========== before: ['1-2*(60-30 +-8.0*173545.880953)-(-4*3)/(16-3*2) '] 60 -30 +-8.0*173545.880953 =-1388337.04762 after: ['1-2*(-1388337.04762-(-4*3)/(16-3*2 )) '] ========== last computing end ========== before: ['1-2 * (-1388337.04762-(-4*3)/(16-3*2) ']-4*3 =-12.0 after: ['1-2*(-1388337.04762 -- 12.0/(16-3*2 )) '] ========== last computing end ========== before: ['1-2*(-1388337.04762 -- 12.0/(16-3*2) '] 16-3*2 = 10.0 after: ['1-2*(-1388337.04762 -- 12.0/10.0) '] =========== last computing end ========== before: ['1-2*(-1388337.0 4762--12.0/10.0) ']-1388337.04762 -- 12.0/10.0 =-1388335.84762 after: ['1-2 *-1388335.84762 '] =========== last computing end ========= my computing results: 2776672.69524 ''' import re, OS, sysdef compute_exponent (arg): "operation index: param expression: return: calculation Result "" val = arg [0] pattern = re. compile (R' \ d + \.? \ D * [\ *] {2} [\ + \-]? \ D + \.? \ D * ') mch = pattern. search (val) if not mch: return content = pattern. search (val ). group () if len (content. split ('**')> 1: n1, n2 = content. split ('**') value = float (n1) ** float (n2) else: pass before, after = pattern. split (val, 1) new_str = "% s" % (before, value, after) arg [0] = new_str compute_exponent (arg) def compute_mul_div (arg ): "Operation multiplication and division: param expression: return: calculation result" val = arg [0] patte Rn = re. compile (R' \ d + \.? \ D * [\ * \/\ % \/] + [\ + \-]? \ D + \. * \ d * ') mch = pattern. search (val) if not mch: return content = pattern. search (val ). group () if len (content. split ('*')> 1: n1, n2 = content. split ('*') value = float (n1) * float (n2) elif len (content. split ('//')> 1: n1, n2 = content. split ('/') value = float (n1) // float (n2) elif len (content. split ('%')> 1: n1, n2 = content. split ('%') value = float (n1) % float (n2) elif len (content. split ('/')> 1: n1, N2 = content. split ('/') value = float (n1)/float (n2) else: pass before, after = pattern. split (val, 1) new_str = "% s" % (before, value, after) arg [0] = new_str compute_mul_div (arg) def compute_add_sub (arg ): "Operation addition and subtraction: param expression: return: calculation result" while True: if arg [0]. _ contains _ ('+-') or arg [0]. _ contains _ ("++") or arg [0]. _ contains _ ('-+') or arg [0]. _ contains _ ("--"): arg [0] = arg [0 ]. Replace ('+-', '-') arg [0] = arg [0]. replace ('++', '+') arg [0] = arg [0]. replace ('-+', '-') arg [0] = arg [0]. replace ('--', '+') else: break if arg [0]. startswith ('-'): arg [1] + = 1 arg [0] = arg [0]. replace ('-', '&') arg [0] = arg [0]. replace ('+', '-') arg [0] = arg [0]. replace ('&', '+') arg [0] = arg [0] [1:] val = arg [0] pattern = re. compile (R' \ d + \.? \ D * [\ + \-] {1} \ d + \.? \ D * ') mch = pattern. search (val) if not mch: return content = pattern. search (val ). group () if len (content. split ('+')> 1: n1, n2 = content. split ('+') value = float (n1) + float (n2) else: n1, n2 = content. split ('-') value = float (n1)-float (n2) before, after = pattern. split (val, 1) new_str = "% s" % (before, value, after) arg [0] = new_str compute_add_sub (arg) def compute (expression ): "Operation addition, subtraction, multiplication, division: param Expression: return: compute_exponent # compute_mul_div (indium) in the processing expression) # add and subtract compute_add_sub (indium) if divmod (indium [1], 2) [1] = 1: result = float (indium [0]) of the processing expression result = result *-1 else: result = float (indium [0]) return resultdef exec_bracket (expression): "" recursive processing of parentheses and calculation: param expression: return: The final calculation result is "" pattern = re. compile (R' \ ([\ + \-\ * \/\ % \/\/\* \ *] * \ D + \. * \ d *) {2,} \) ') # If no parentheses exist in the expression, directly call the function responsible for calculation and return the expression result, for example: 2*1-82 + 444 # if not re. search ('\ ([\ + \-\ * \/] * \ d + \. * \ d *) {2,} \) ', expression): if not pattern. search (expression): final = compute (expression) return final # obtain the first parentheses containing only numbers/decimals and operators # For example: #['1-2*(60-30 + (-40.0/5) * (9-2*5/3 + 7/3*99/4*2998 + 10*568/14 )) -(-4*3)/(16-3*2) '] # Find Out: (-40.0/5) content = pattern. search (expression ). group () # split expression, I .e :# Set ['1-2*(60-30 + (-40.0/5) * (9-2*5/3 + 7/3*99/4*2998 + 10*568/14 )) -(-4*3)/(16-3*2) '] # Separate the three parts: ['1-2*(60-30 + (-40.0/5) * (9-2*5/3 + 7/3*99/4*2998 + 10*568/14 )) -(-4*3)/(16-3*2) '] before, nothing, after = pattern. split (expression, 1) print ('before: ', expression) content = content [1: len (content)-1] # calculation, extracted representation (-40.0/5), and the live result is:-40.0/5 =-8.0 ret = compute (content) print ('% s = % s' % (content, ret) # splice the execution result, ['1-2*(60-30 + (-8.0*(9-2*5/3 + 7/3*99/4*2998 + 10*568/14)-(-4*3) /(16-3*2) '] expression = "% s" % (before, ret, after) print ('after:', expression) print ("=" * 10, 'previous result is ', "=" * 10) # The loop continues the next brace processing operation. This contains the processed expression, that is: #['1-2*(60-30 +-8.0*(9-2*5/3 + 7/3*99/4*2998 + 10*568/14 )) -(-4*3)/(16-3*2) '] # This repeats until the expression no longer contains the brackets return exec_bracket (expression) # purpose of using _ name _: # Only python index is executed. the following code only Run # if others import this module, the following code does not run if _ name _ = "_ main _": flag = True OS. system ('clear ') ### clear screen ### print ('\ n ============================ ========================================= ') print ('\ 033 [33 m welcome calculator: \ 033 [0m ') print ('\ n ======================================== ============================= ') while flag: calculate_input = raw_input ('\ 033 [32 m, enter the calculated expression | (Exit: q) \ 033 [0m') calculate_input = re. sub ('\ s *', '', calculate_indium Ut) if len (calculate_input) = 0: continue elif calculate_input = 'q': sys. exit ('exit Project') elif re. search ('[^ 0-9 \. \-\ + \ * \/\ % \/\ * \ (\)] ', calculate_input): print (' \ 033 [31 m input error, please enter it again !!! \ 033 [0m') else: result = exec_bracket (calculate_input) print ('the expression result is % s' % result)Calculator

 

4. There is no big difference between python2.7 and python3.4, so you only need one version.

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.