A complete example of the calculator function designed and implemented by Python.

Source: Internet
Author: User

A complete example of the calculator function designed and implemented by Python.

This example describes the calculator function designed and implemented by Python. We will share this with you for your reference. The details are as follows:

Use PYTHON to design and process the functions of a calculator, such:

1-2*(60-30 + (-40/5) * (9-2*5/3 + 7/3*99/4*2998 + 10*568/14)-(-4*3) /(16-3*2 ))

My basic ideas for processing and computing are:

The solution is to prioritize the calculation of inner brackets-Calculation of outer parentheses-the principle of first multiplication, division, and addition and subtraction:

1. RegEx processes the string entered by the user, and then determines whether the calculation formula contains parentheses. If yes, RegEx the calculation formula first to obtain each data in the innermost layer, then calculate

The regular expression used is:

inner = re.search("\([^()]*\)", calc_input)

2. Replace the result calculated by the formula with parentheses with the original initial formula. The repeated operators are processed before calculation.

The function for repeated operations to be processed is

def del_double(str):  str = str.replace("++", "+")  str = str.replace("--", "-")  str = str.replace("+-","-")  str = str.replace("- -","-")  str = str.replace("+ +","+")  return str

3. Remove the parentheses from the inside and out of the brackets for calculation, and replace the positions.

calc_input = calc_input.replace(inner.group(), str(ret))

Replace the calculated results with the original calculation formula.

4. Finally, the formula without parentheses is obtained. Merge and call the calculation control function for calculation. Note that the negative signs and numbers are processed together with *. Other values are acceptable.

The specific logic diagram is as follows:

The complete code is as follows:

#! /Usr/bin/env python3.5 #-*-coding: utf8-*-import rea = r'1-2 * (60-30 + (-40/5) * (9-2*5/3 + 7/3*99/4*2998 + 10*568/14)-(-4*3)/(16-3*2 )) '# */operation function def shengchu (str): calc = re. split ("[*/]", str) # Use */to separate the formula OP = re. findall ("[*/]", str) # Find all * And/ret = None for index, I in enumerate (calc): if ret: if OP [index-1] = "*": ret * = float (I) elif OP [index-1] = "/": ret/= float (I) else: ret = float (I) retu Rn ret # Remove the repeated operation and process the Special Column +-symbol def del_double (str): str = str. replace ("++", "+") str = str. replace ("--", "-") str = str. replace ("+-", "-") str = str. replace ("--", "-") str = str. replace ("++", "+") return str # Calculate the master control function def calc_contrl (str): tag = False str = str. strip ("()") # Remove the outermost parentheses str = del_double (str) # Call a function to process repeated operations such as find _ = re. findall ("[+-]", str) # obtain all +-operator splits _ = re. split ("[+-]", str) # Use the +-operator to separate regular expressions., Only the */operator if len (split _ [0] is left after the split. strip () = 0: # special processing: split _ [1] = find _ [0] + split _ [1] # "-" before the first number is processed, obtain a new signed number # When "-" is the negative number before the first number is processed, if len (split _) = 3 and len (find _) = 2: tag = True del split _ [0] # Delete the original split number del find _ [0] else: del split _ [0] # Delete the original split number del find _ [0] # Delete the original split operator for index, I in enumerate (split _): # divide by X or the ending number if I. endswith ("*") or I. endswith ("/"): split _ [index] = Split _ [index] + find _ [index] + split _ [index + 1] del split _ [index + 1] del find _ [index] for index, I in enumerate (split _): if re. search ("[*/]", I): # Calculate the formula sub_res = shengchu (I) containing) # Call the remaining division function split _ [index] = sub_res # Calculate the addition and subtraction res = None for index, I in enumerate (split _): if res: if find _ [index-1] = "+": res + = float (I) elif find _ [index-1] = "-": # if two negative values are subtracted, add them together. Otherwise, subtract if tag = True: res + = float (I) el. Se: res-= float (I) else: # if I is null when no parentheses exist, if I! = "": Res = float (I) return resif _ name _ = '_ main _': calc_input = input ("Enter the calculation formula. The default value is: % s: "% ). strip () try: if len (calc_input) = 0: calc_input = a calc_input = r '% s' % calc_input # perform special processing, keep character original shape flag = True # initialization flag result = None # initialize calculation result # loop processing parentheses while flag: inner = re. search ("\ ([^ ()] * \)", calc_input) # obtain the single content in the innermost brackets # print (inner. group () # if inner: ret = calc_contrl (inner. group () # Call Calculation control function calc_input = calc_input.replace (inner. group (), str (ret) # Replace the operation result with the print string corresponding to the original processed index value ("processing the operation in parentheses [% s] the result is: % s "% (inner. group (), str (ret) # flag = True # Calculate else: ret = calc_contrl (calc_input) print ("the final calculation result is: % s "% ret) # flag = False when T: print (" the formula you entered is incorrect. Please enter it again! ")

PS: here we recommend several js-implemented computing tools for your reference:

Calculation tool for online mona1 functions (equations:
Http://tools.jb51.net/jisuanqi/equ_jisuanqi

Scientific calculator online use _ advanced calculator online computing:
Http://tools.jb51.net/jisuanqi/jsqkexue

Online calculator _ standard calculator:
Http://tools.jb51.net/jisuanqi/jsq

Supplement:

PYTHON Regular Expressions:

Mode Description
^ Match the start of a string
$ Matches the end of a string.
. Match any character. Except for line breaks, when the re. DOTALL mark is specified, it can match any character including line breaks.
[...] It is used to represent a group of characters and is listed separately: [amk] matches 'A', 'M', or 'K
[^...] Character not in []: [^ abc] matches characters other than a, B, and c.
Re * Matches zero or multiple expressions.
Re + Matches one or more expressions.
Re? Matches 0 or 1 segment defined by the previous regular expression. It is not greedy.
Re {n}
Re {n ,} Exact match with n previous expressions.
Re {n, m} Match the segments defined by the regular expression n to m times. Greedy Mode
A | B Match a or B
(Re) G matches the expression in parentheses, which also represents a group
(? Imx) A regular expression contains three optional symbols: I, m, or x. Only the area in the brackets is affected.
(? -Imx) The regular expression disables the I, m, or x flag. Only the area in the brackets is affected.
(? : Re) Similar to (...), but does not represent a group
(? Imx: re) Use an I, m, or x flag in parentheses
(? -Imx: re) Do not use the I, m, or x optional flag in parentheses
(? #...) Note.
(? = Re) The forward positive identifier. If the regular expression is included in the regular expression, it indicates that the match is successful at the current position. Otherwise, the match fails. However, once the contained expression has been tried, the matching engine has not improved at all; the rest of the pattern also needs to try to the right of the separator.
(?! Re) A forward negative identifier. Opposite to the positive identifier. The expression contained in the string cannot match the current position of the string.
(?> Re) Matching independent mode, eliminating backtracking.
\ W Match letters and numbers
\ W Match non-alphanumeric characters
\ S Matches any blank character, which is equivalent to [\ t \ n \ r \ f].
\ S Match any non-empty characters
\ D Matching any number is equivalent to [0-9].
\ D Match any non-digit
\ Match string
\ Z Match string ends. If there is a line break, only the end string before the line break is matched. C
\ Z Match string ends
\ G The position where the last match is completed.
\ B Match A Word boundary, that is, the position between a word and a space. For example, 'er \ B 'can match 'er' in "never", but cannot match 'er 'in "verb '.
\ B Match non-word boundary. 'Er \ B 'can match 'er' in "verb", but cannot match 'er 'in "never '.
\ N, \ t, and so on. Match A linefeed. Match a tab. And so on
\ 1... \ 9 The child expression that matches the nth group.
\ 10 Match the child expression of the nth group if it matches. Otherwise, it refers to the expression of the octal verification code.

In addition, we provide two very convenient Regular Expression tools for your reference:

JavaScript Regular Expression online testing tool:
Http://tools.jb51.net/regex/javascript

Regular Expression generation tool:
Http://tools.jb51.net/regex/create_reg

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.