Home  >  Article  >  Backend Development  >  Complete example sharing of Python design calculator function implementation

Complete example sharing of Python design calculator function implementation

黄舟
黄舟Original
2017-08-20 10:53:123746browse

This article mainly introduces the calculator function designed and implemented in Python. It analyzes the regular, string and numerical operation and other related operating skills of Python3.5 to implement the calculator function in the form of a complete example. Friends in need can refer to the following

The example in this article describes the calculator function designed and implemented in Python. Share it with everyone for your reference, the details are as follows:

By using PYTHON to design and process the functions of the calculator, such as:

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 idea of ​​​​processing calculations is:

The problem-solving idea is that the inner bracket operations need to be processed first-the outer bracket operations-the principle of multiplication and division first and then addition and subtraction:

1. Regularly process the string input by the user, and then judge it to determine whether the calculation formula has parentheses. If so, first regularize the calculation formula, first obtain each data in the innermost layer, and then calculate them one by one

The regular rules to be used are:


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

2. Replace the original initial formula with the result calculated by the bracketed calculation formula. position, the repeat operators are processed separately before calculation

The function of repeated operations that needs 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, and then from the inside to the outside in sequence Remove the brackets and perform the calculation, and replace the positions with


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

. Replace the calculated results with the original calculation formula

4. Finally, get the formula without brackets. , merge and call the calculation control function for calculation. What needs to be paid attention to is the processing of negative signs and numbers together with *, and the rest is okay.

The specific logic diagram is:

##The following is the complete code:


#!/usr/bin/env python3.5
# -*-coding:utf8-*-
import re
a =r'1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 ))- (-4*3)/(16-3*2))'
# */运算函数
def shengchu(str):
  calc = re.split("[*/]",str)   #用*/分割公式
  OP = re.findall("[*/]",str)  #找出所有*和/号
  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)
  return ret
# 去掉重复运算,和处理特列+-符号
def del_double(str):
  str = str.replace("++", "+")
  str = str.replace("--", "-")
  str = str.replace("+-","-")
  str = str.replace("- -","-")
  str = str.replace("+ +","+")
  return str
# 计算主控制函数
def calc_contrl(str):
  tag = False
  str = str.strip("()") # 去掉最外面的括号
  str = del_double(str) # 调用函数处理重复运算
  find_ = re.findall("[+-]",str) # 获取所有+- 操作符
  split_ = re.split("[+-]",str) #正则处理 以+-操作符进行分割,分割后 只剩*/运算符
  if len(split_[0].strip()) == 0: # 特殊处理
    split_[1] = find_[0] + split_[1] # 处理第一个数字前有“-”的情况,得到新的带符号的数字
    # 处理第一个数字前为负数“-",时的情况,可能后面的操作符为“-”则进行标记
    if len(split_) == 3 and len(find_) ==2:
      tag =True
      del split_[0] # 删除原分割数字
      del find_[0]
    else:
      del split_[0] # 删除原分割数字
      del find_[0] # 删除原分割运算符
  for index, i in enumerate(split_):
    # 去除以*或/结尾的运算数字
    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): # 先计算含*/的公式
      sub_res = shengchu(i) #调用剩除函数
      split_[index] = sub_res
  # 再计算加减
  res = None
  for index, i in enumerate(split_):
    if res:
      if find_[index-1] == "+":
        res += float(i)
      elif find_[index-1] == "-":
        # 如果是两个负数相减则将其相加,否则相减
        if tag == True:
          res += float(i)
        else:
          res -= float(i)
    else:
      # 处理没有括号时会出现i 为空的情况
      if i != "":
        res = float(i)
  return res
if __name__ == '__main__':
  calc_input = input("请输入计算公式,默认为:%s:" %a).strip()
  try:
    if len(calc_input) ==0:
      calc_input = a
    calc_input = r'%s'%calc_input # 做特殊处理,保持字符原形
    flag = True  # 初始化标志位
    result = None  # 初始化计算结果
    # 循环处理去括号
    while flag:
      inner = re.search("\([^()]*\)", calc_input)# 先获取最里层括号内的单一内容
      #print(inner.group())
      # 有括号时计算
      if inner:
        ret = calc_contrl(inner.group()) # 调用计算控制函数
        calc_input = calc_input.replace(inner.group(), str(ret)) # 将运算结果,替换原处理索引值处对应的字符串
        print("处理括号内的运算[%s]结果是:%s" % (inner.group(),str(ret)))
        #flag = True
      # 没有括号时计算
      else:
        ret = calc_contrl(calc_input)
        print("最终计算结果为:%s"% ret)
        #结束计算标志
        flag = False
  except:
    print("你输入的公式有误请重新输入!")

Supplement:

PYTHON regular expression list:

## (?= re)Forward positive delimiter. Succeeds if the contained regular expression, represented by ... , successfully matches the current position, otherwise it fails. But once the contained expression has been tried, the matching engine doesn't improve at all; the remainder of the pattern still has to try the right side of the delimiter. (?! re)Forward negative delimiter. Opposite of positive delimiter; succeeds when the contained expression cannot be matched at the current position of the string (?> re)Matched independent pattern, omitted Go backtrack. \wMatches alphanumeric characters\WMatches non-alphanumeric characters\s matches any whitespace character, equivalent to [\t\n\r\f].\S Matches any non-empty character \d Matches any number, equivalent to [0-9].\DMatch any non-digit\AMatch the beginning of the string\Z Matches the end of the string. If there is a newline, only the end of the string before the newline is matched. c\z Matches the end of the string \G Matches the position where the last match is completed. \b Matches a word boundary, which refers to the position between a word and a space. For example, 'er\b' matches 'er' in "never" but not in "verb". \B Matches non-word boundaries. 'er\B' matches 'er' in "verb" but not in "never". \n, \t, etc. matches a newline character. Matches a tab character. etc. \1...\9 matches the subexpression of the nth group. \10 Matches the subexpression of the nth group if it is matched. Otherwise it refers to the expression of the octal character code.
Pattern Description
^ Match the beginning of the string
$ Matches the end of the string.
. Matches any character except newline characters. When the re.DOTALL flag is specified, it can match any character including newline characters.
[...] is used to represent a group of characters, listed separately: [amk] matches 'a', 'm' or 'k
[^...] Characters not in []: [^abc] matches characters other than a, b, c.
re* Matches 0 or more expressions.
re+ Matches one or more expressions.
#re? Match 0 or 1 fragment defined by the previous regular expression, non-greedy way
re{ n}
re{ n,} Exactly matches n previous expressions.
re{ n, m} Match n to m times the fragment defined by the previous regular expression, greedy way
a| b matches a or b
(re) G matches the expression in brackets and also represents a group
(?imx) Regular expressions contain three optional flags: i, m, or x. Only affects the area in brackets.
(?-imx) Regular expression turns off the i, m, or x optional flags. Only affects the area in brackets.
(?: re) Similar to (...), but does not represent a group
(?imx : re) Use i, m, or x in parentheses optional flag
(?-imx: re) in parentheses Do not use i, m, or x optional flags
(?#...) Comments.

The above is the detailed content of Complete example sharing of Python design calculator function implementation. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn