Day4 job calculator, day4 Calculator

Source: Internet
Author: User

Day4 job calculator, day4 Calculator

Job: calculator Development

(1) implements addition, subtraction, multiplication, division, and extension priority resolution;

(2) user input 1-2*(60-30 + (-40/5) * (-9-2*5/-3 + 7/3*99/4*2998 + 10*568/14)-(-4*3)/(16-3*2 )) after a similar formula is used, you must parse the (), +,-, *,/, and formula in it and calculate the result, the result must be consistent with the result obtained by the real calculator.

Ideas:

(1) first, we need to find the content in the memory brackets and use regular expressions. Here, in the memory brackets, we select a complex one (-9-2*5/-3 + 7/3*99/4*2998 + 10*568/14 );

(2) After finding the content in the memory parentheses, we only need to calculate the content in the inner brackets, and then we need to repeat the memory parentheses;

(3) first remove the memory string brackets-9-2*5/-3 + 7/3*99/4*2998 + 10*568/14;

(4) Then we are correcting it, removing spaces in the string, converting "+-" into "-", and converting "--" into "=;

(5)-9-2*5/-3 + 7/3*99/4*2998 + 10*568/14, which is obtained above. Next, we will split it, split with "+-" and extract all "+-" in the string, put them in two lists: sign = ["-","-","-", "+", "+"], formula_list = ["", "9", "2*5/", "3", "7/3*99/4*2998 ", "10*568/14"];

(6) Although we have obtained two lists above, we found that formula_list contains "", which will affect our subsequent operations. The list also contains "2*5 /", it indicates that the list in this place is followed by a negative number. We must process it and connect it to make it correct;

(7) Process "" And get sign = ["-", "-", "+", "+"], formula_list = ["-9 ", "2*5/", "3", "7/3x99/4*2998", "10*568/14"]

(8) Process "2*5/". Here we need to splice the negative number next to it and get sign = ["-", "+", "+"], formula_list = ["-9", "2*5/-3", "7/3*99/4*2998", "10*568/14"]

(9) Next, we will execute the multiplication and division operation, and pass the list formula_list to the function for processing the multiplication and division, so that the multiplication and division operations in the list are obtained in the following format;

(10) formula_list = ["-9",-3.33334, 173134.00001, 405.71]. Then, return the list to perform addition and subtraction;

(11) process the addition and subtraction function to receive the parameter, and perform the addition and subtraction operation. The result is res;

(12) Use res to replace the regular-matching string. If the above program keeps repeating, the result will be obtained;

Insert a code written by someone else. This is the best code I have ever written. The logic and thinking skills of a person are closely linked. I have read the logic and thinking skills of a person several times and got the principle, and insist on thanking you again. As follows:

 

Import redef operator_update (formula): # Remove null characters from the formula. The update operator processes formula = formula. replace ("", "") # Remove the null character formula = formula. replace ("+-", "-") formula = formula. replace ("--", "+") return formuladef calc_muldiv (formula_list): ''' multiplication and division in the formula: param formula: List: return: ''' for index, element in enumerate (formula_list): if "*" in element or "/" in element: operators = re. findall ("[*/]", element) calc_list = re. split ("[*/]", element) num = None for I, e in enumerate (calc_list): if num: if operators [I-1] = "*": num * = float (e) elif operators [I-1] = "/": num/= float (e) else: num = float (e) formula_list [index] = num return formula_listdef calc_plumin (operators, num_list): ''' addition and subtraction of list numbers: param operators: Operator list: param num_list: list of numbers for calculation: return: return the computation result '''num = None for I, e in enumerate (num_list): if num: if operators [I-1] = "+ ": num + = float (e) elif operators [I-1] = "-": num-= float (e) else: num = float (e) return numdef merge (plus_minus_operator, multiply_divide_list: param formula_list: return: ''' for index, element in enumerate (multiply_divide_list): if element. endswith ("*") or element. endswith ("/"): multiply_divide_list [index] = element + partition [index] + multiply_divide_list [index + 1] del multiply_divide_list [index + 1] del partition [index] return merge (partition, multiply_divide_list) return response, multiply_divide_listdef bracket_calc (formula): ''' calculates the formula at the bottom of the brackets: param formula: return: ''' formula = re. sub ("[()]", "", formula) # Remove () formula = operator_update (formula) plus_minus_operator = re. findall ("[+-]", formula) # list '+'-'operator multiply_divide_list = re. split ("[+-]", formula) # if the first character in the multiply_divide_list [0] = "": # multiply_divide_list list is null, indicates that a number is a negative number multiply_divide_list [1] = "-" + multiply_divide_list [1] del limit [0] del multiply_divide_list [0] res = merge (limit, multiply_divide_list) plus_minus_operator = res [0] # list '+'-'operator merge processing multiply_divide_list = res [1] plus_minus_list = calc_muldiv (multiply_divide_list) # generate a list of addition and subtraction operations only. res = calc_plumin (plus_minus_operator, plus_minus_list) return resdef calculate (formula): ''' main entry of the computing program, the main logic is to calculate the value in the extension number first, calculate it, then calculate the multiplication and division, and then add or subtract ''' while True: formula_depth = re. search ("\ ([^ ()] + \)", formula) if formula_depth: formula_depth = formula_depth.group () res = bracket_calc (formula_depth) formula = formula. replace (formula_depth, str (res) print ("\ 33 [34; 1 m % s \ 33 [0 m" % (formula) else: res = bracket_calc (formula) print ("\ 33 [31; 1 m result: % s \ 33 [0 m" % (res) exit () if _ name _ = '_ main __': formula = "1-2*(60-30 + (-9-2-5-2 *-3-5/3-40*4/2-3/5 + 6*3) * (-9-2-5-2*5/3 + 7/3*99/4*2998 + 10*568/14)-(-4*3)/(16-3*2 )) "calculate (formula)

 

I thanked myself for the above ideas and did not read the code. I thanked myself according to my own ideas. I still need to study it. Many methods are used in it. String splitting, findall (), and many other methods, such as-=, + =, * =,/=, if the element does not exist, and if it is created first, when the values in the element are traversed and then multiplied and divided:

Import re # import the regular expression module formula = "1-2*(60-30 + (-9-2*5/-3 + 7/3*99/4*2998 + 10*568/14) * (-40/5)-(-4*3)/(16-3*2) "def formula_update (formula_deep): # trim the string formula_deep to remove spaces, convert +-to-, convert -- + operation formula_deep = formula_deep.replace ("", "") # Remove spaces formula_deep = formula_deep.replace ("+ -","-") formula_deep = formula_deep.replace ("--", "+") return formula_deepdef formula_correct (operator_signs, formula_list): if formula_list [0] = "": # If the first element in the list is "", it indicates that the element is preceded by a "-" number. At this time, there is no need to separate it. Because it is-9, an error occurs during the split, therefore, determine formula_list [1] = "-" + formula_list [1] del operator_signs [0] del formula_list [0] print (operator_signs) print (formula_list) for I, e in enumerate (formula_list): if e. endswith ("*") or e. endswith ("/"): formula_list [I] = e + "-" + formula_list [I + 1] del operator_signs [I] del formula_list [I + 1] return operator_signs, formula_listdef muldiv (formula_list): for index, element in enumerate (formula_list): if "*" in element or "/" in element: muldiv_signs = re. findall ("[/*]", element) muldiv_lists = re. split ("[/*]", element) num = None for I, e in enumerate (muldiv_lists): if num: if muldiv_signs [I-1] = "*": num * = float (e) elif muldiv_signs [I-1] = "/": num/= float (e) else: num = float (e) formula_list [index] = num return formula_listdef add_min (operator_signs, formula_list): num = None for I, e in enumerate (formula_list): if num: if operator_signs [I-1] = "+": num + = float (e) elif operator_signs [I-1] = "-": num-= float (e) else: num = float (e) return numdef handle (formula_deep): formula_deep = re. sub ("[()]", "", formula_deep) # Remove the parentheses of the string and then execute the following command to remove spaces and convert +-and -- formula_deep = formula_update (formula_deep) # trim the string, remove spaces, and perform operator_signs = re. findall ("[+-]", formula_deep) # generate a list of operators in the string. Because multiplication is performed first, the original operator number must be retained, so that after multiplication, add or subtract formula_list = re. split ("[+-]", formula_deep) # generate a list. The list is used to execute the operation element. In the list, you must correct ret = formula_correct (operator_signs, formula_list) in some unreasonable ways) # modify the list. The element starting with the list is "" and ending "/", or "*", operator_signs = ret [0] # obtain the new operator number formula_list = ret [1] # obtain the new operation list # execute the multiplication operation formula_list = muldiv (formula_list) # To obtain a list without multiplication and division, add and subtract res = add_min (operator_signs, formula_list) return resdef main (formula): while True: formula_deep = re. search ("\ ([^ ()] + \)", formula) # matches the inner brackets, processes the content in the memory parentheses, and loops back and forth to meet the condition if formula_deep: # When the Matching content is not blank, execute the program. If no matching brackets are found, it indicates that the matching is over. The matching conditions are not included in the brackets formula_deep = formula_deep.group () res = handle (formula_deep) formula = formula. replace (formula_deep, str (res) else: res = handle (formula) print (res) exit () if _ name _ = "_ main __": formula = "1-2*(60-30 + (-40/5) * (-9-2*5/-3 + 7/3*99/4*2998 + 10*568/14 )) -(-4*3)/(16-3*2) "main (formula)

The running result is as follows:

[]
['-40/5']
['-', '-', '+', '+']
['-9', '2*5/', '3', '2017*7/3*99/4 ', '10*2998']
['-', '-']
['60', '30', '8. 0*173534.54761904766 ']
[]
['-4 * 3']
['-']
['16', '3 * 2']
['+']
['-100', '12. 1388246.3809523813. 0']
['-', '-']
['1', '2 * ', '192. 100']
Result: 2776491.3619047627

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.