Python implements two examples of calculator functions

  • 2020-06-19 10:39:21
  • OfStack

This article is an example of Python to share the calculator function example code for your reference, the specific content is as follows

1. Simple calculator


# To calculate 1 When you have an expression, you must first evaluate the parentheses, then the multiplication and division, and then the addition and subtraction 
import re
# 1. Go to the brackets 
def remove_kuohao(expression):
  '''
   This is a 1 A function that removes parentheses 
  :param expression:  The expression passed in 
  :return:  The result of the calculation 
  '''
  while True:
    ret = re.search(r'\([^(]*?\)',expression) # I'm going to use the regular matches to the parentheses 
    if ret: # If you have parentheses 
      re_expression = ret.group() # So let's put the parentheses that we found group()1 under 
      # print(re_expression)
      res = jianhua(re_expression.strip('()')) # It's in parentheses */-+ Don't 1 Yes, it's defined again 1 A function that simplifies this expression 
      #  If it's multiplication, it's multiplication, if it's division, it's division, etc., so it's called directly jianhua This function, of course, this expression 
      #  I've got the parentheses, by the way I've got the parentheses, and I'm just going to do the calculation without the parentheses 
      expression = expression.replace(re_expression,str(res)) # Put the result back: just put the expression in parentheses 
                                  #  So let's replace that with what we're doing now 
      # print(expression)
      continue
    break
  res = jianhua(expression)
  return res
# Simplify the algorithm 
def jianhua(re_expression):
  while True:
    #  Match multiplication and division 
    ret = re.search(r'\d+\.*?\d*[*/]\-?\d+\.?\d*', re_expression) # Use regular matching multiplication and division 
    if ret: #  If there is a match * or / Just execute the following code 
      chengchu_expression = ret.group() # first group1 I'm going to get an expression with multiplication and division 
      res = chengchu(chengchu_expression) # Calls the multiplication and division function 
      re_expression = re_expression.replace(chengchu_expression, str(res)) # I'm going to substitute the multiplication and division with the result 
      re_expression =chulifuhao(re_expression) # A function that handles symbols is called 
      # print(re_expression)
      continue
    break
  #  Match addition and subtraction 
  num = re.findall(r'[+-]?\d+\.?\d*', re_expression)# When there's no multiplication or division, let's just match the addition and subtraction, 
  if len(num) > 1: # If the length of the matched expression is greater than 1 But whether it's addition or subtraction, let's do addition. because float Whatever comes out of it 
    mynum = 0
    for i in num:
      mynum += float(i)
    return mynum
  else:
    return num[0]
# 3. You compute two Numbers +-*/
def chengchu(expression):
  if '*' in expression:
    x,y = expression.split('*')
    return float(x)*float(y) # Returns the result of the multiplication operation   And let res receive 
  if '/' in expression:
    x, y = expression.split('/')
    return float(x)/float(y)  # Returns the result of the multiplication operation   And let res receive 

def chulifuhao(expression):
  if '--' in expression:
    expression = expression.replace('--','+')
  if '++' in expression:
    expression = expression.replace('++','+')
  if '+-' in expression:
    expression = expression.replace('+-','-')
  if '-+' in expression:
    expression = expression.replace('-+','-')
  return expression # Returns the result 

cmd = input(' Please enter the expression you want to evaluate: >>')
# s = '1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )'
new_s = cmd.replace(' ', '') # I'm going to leave out all the Spaces 
# print(new_s)
ret = remove_kuohao(new_s) # Call the function that removes the parentheses 1 Step operation 
print(ret)

A more advanced calculator


import re
from functools import reduce
from tkinter import *
''' Handles special - sign operations '''


def minus_operation(expresstion):
  minus_operators = re.split("-", expresstion)
  calc_list = re.findall("[0-9]", expresstion)
  if minus_operators[0] == "":
    calc_list[0] = '-%s' % calc_list[0]
  res = reduce(lambda x, y: float(x) - float(y), calc_list)
  print(">>>>>>>>>>>>>> A minus sign [%s] Operation results :" % expresstion, res)
  return res

'''reduce() right sequence Continuous use function,  If you don't give initial,  Is the first 1 Secondary call passing sequence Two elements of ,
 After the first 1 The result of the call sequence Under the 1 I'm going to pass to function'''

''' Handles double operation symbols '''


def del_duplicates(expresstion):
  expresstion = expresstion.replace("++", "+")
  expresstion = expresstion.replace("--", "-")
  expresstion = expresstion.replace("+-", "-")
  expresstion = expresstion.replace("--", "+")
  expresstion = expresstion.replace('- -', "+")
  return expresstion
''' * / function '''
def mutiply_dividend(expresstion):
  calc_list = re.split("[*/]", expresstion) #  With a *  or / Integral formula 
  operators = re.findall("[*/]", expresstion) #  Find all the * and/signs 
  res = None
  for index, i in enumerate(calc_list):
    if res:
      if operators[index - 1] == '*':
        res *= float(i)
      elif operators[index - 1] == '/':
        res /= float(i)
    else:
      res = float(i)
  procession0 = "[%s] Operation results =" % expresstion, res
  # final_result.insert(END, procession0) #  Insert the form 
  print(procession0)
  return res

''' Handles arithmetic symbol order confusion '''
def special_features(plus_and_minus_operators, multiply_and_dividend):
  for index, i in enumerate(multiply_and_dividend):
    i = i.strip()
    if i.endswith("*") or i.endswith("/"):
      multiply_and_dividend[index] = multiply_and_dividend[index] + plus_and_minus_operators[index] + multiply_and_dividend[index + 1]
      del multiply_and_dividend[index + 1]
      del plus_and_minus_operators[index]
    return plus_and_minus_operators, multiply_and_dividend

def minus_special(operator_list, calc_list):
  for index, i in enumerate(calc_list):
    if i == '':
      calc_list[index + 1] = i + calc_list[index + 1].strip()
''' I'm dividing by the formula for theta +- * / '''
def figure_up(expresstion):
  expresstion = expresstion.strip("()") #  Get rid of the outside brackets 
  expresstion = del_duplicates(expresstion) #  Get rid of the repeat +- 
  plus_and_minus_operators = re.findall("[+-]", expresstion)
  multiply_and_dividend = re.split("[+-]", expresstion)
  if len(multiply_and_dividend[0].strip()) == 0:
    multiply_and_dividend[1] = plus_and_minus_operators[0] + multiply_and_dividend[1]
    del multiply_and_dividend[0]
    del plus_and_minus_operators[0]
  plus_and_minus_operators, multiply_and_dividend = special_features(plus_and_minus_operators, multiply_and_dividend)
  for index, i in enumerate(multiply_and_dividend):
    if re.search("[*/]", i):
      sub_res = mutiply_dividend(i)
      multiply_and_dividend[index] = sub_res
  # print(multiply_and_dividend, plus_and_minus_operators) #  To calculate 
  final_res = None
  for index, item in enumerate(multiply_and_dividend):
    if final_res:
      if plus_and_minus_operators[index - 1] == '+':
        final_res += float(item)
      elif plus_and_minus_operators[index - 1] == '-':
        final_res -= float(item)
    else:
      final_res = float(item)
      procession = '[%s] The calculation results :' % expresstion, final_res
    # final_result.insert(END, procession) #  Insert the form 
    # print(procession)
  return final_res
""" Main function: operation logic: first calculate the value in the extension sign , And then we can multiply and divide , Then the add and subtract """
def calculate():
  expresstion = expresstions.get() #  Gets the input field value 
  flage = True
  calculate_res = None #  The initial calculation result is None
  while flage:
    m = re.search("\([^()]*\)", expresstion) #  Find the innermost () first. 
  # pattern = re.compile(r"\([^()]*\)")
  # m = pattern.match(expresstion)
    if m:
      sub_res = figure_up(m.group()) #  Compute the formula in () 
      expresstion = expresstion.replace(m.group(), str(sub_res)) #  I'm done and I'm going to replace the formula 
    else:
      # print('--------------- The parentheses have been calculated --------------')
      procession1 = " Final calculation result :%s\n"%figure_up(expresstion)
      print(procession1)
      final_result.insert(END, procession1) #  Insert the form 
      # print('\033[31m Final calculation result :', figure_up(expresstion))
      flage = False

if __name__ == "__main__":
# res = calculate("1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )")
  window = Tk() ### Create a form 
  window.title(' The calculator ') ### Naming the form 
  frame1 = Frame(window) ### The framework 1
  frame1.pack() ### Place the 
  frame2 = Frame(window) ### The framework 2
  frame2.pack() ### Place the 
  lable = Label(frame1, text=" Please enter the formula: ") ### Text labels 
  lable.pack()
  expresstions = StringVar() ### Input field property, string 
  entryname = Entry(frame1, textvariable=expresstions) ### Text input box 
  bt_get_expresstions = Button(frame1, text=" submit ", command=calculate) ### Button widgets 
  bt_get_expresstions.pack()
  entryname.pack()
  lable.grid_slaves(row=1,column=1)
  entryname.grid_slaves(row=1,column=1)
  bt_get_expresstions.grid_slaves(row=1,column=3)
  final_result = Text(frame2) ### Calculation results display box 
  final_result.tag_config("here", background="yellow", foreground="blue")
  final_result.pack()
  window.mainloop() ### Event loop 

Related articles: