[Python] simple calculator implementation (4)

Solution idea: Finally, let's take a look at the simplest operation function and judgment operator function.

Define the function: def calculate(n1, n2, operator)

  • param n1: float
  • param n2: float
  • param operator: + - * /
  • return: float
def calculate(n1, n2, operator):
    result = 0
    if operator == "+":
        result = n1 + n2
    if operator == "-":
        result = n1 - n2
    if operator == "*":
        result = n1 * n2
    if operator == "/":
        result = n1 / n2
    return result

Define the function: def is_operator(e)

  • param e:str
  • return: bool
def is_operator(e):
    # opers的数据结构是列表
    opers = ['+', '-', '*', '/', '(', ')']
    return True if e in opers else False


final call

Two variables result and _ are defined here to receive the two lists returned by final_calc, namely the number stack and the operator stack. Since there must be only one result, there is only one element in the list result, and it can be viewed by result[0].

if __name__ == '__main__':
    formula = input('请输入:\n')
    print("算式:", formula)
    formula_list = formula_format(formula)
    result, _ = final_calc(formula_list)
    print("计算结果:", result[0])

final summary

Abstract several functions:

  • A function that calculates the result of "an expression composed of two numbers and operators" when the stack is popped.
  • A function that determines whether an element is a number or an operator.
  • Functions that process calculations as lists. For example: '-1-2*((-2+3)+(-2/2))' should be processed as: ['-1', '-', '2', '*', '(', '(', '-2', '+', '3', ')', '+', '(', '-2', '/', '2', ')', ')'] .
  • Decision function, which decides whether to push to the stack, pop the stack for operation, or pop the stack for discarding.
  • The main function traverses the list of calculations and calculates the final result.

Guess you like

Origin blog.csdn.net/m0_64140451/article/details/131747492