[Python] simple calculator implementation (2)

Solution: Next, we need to push the separated numbers and operators onto the stack. Before that, we need a function to determine the priority order of operators. At that time, according to the judgment result of the function, it is decided whether to push or pop the stack.

Define the function: def decision(tail_op, now_op)

  • tail_op: the last operator of the operator stack
  • param now_op: the current operator taken from the calculation list
  • return: 1 means pop the stack and operate, 0 means pop the stack, -1 means push the stack

Step 1: Define four operator precedence levels.

# 优先级由低到高
rate1 = ['+', '-']
rate2 = ['*', '/']
rate3 = ['(']
rate4 = [')']

Step 2: Compare the current operator with the last operator in the operator stack, that is, the previous operator.

Case 1: If the top of the stack is not a parenthesis "(", if the current operator (except ")") has a higher priority, it will be pushed to the stack at that time; if the current operator priority is equal to or less than the previous operator priority, Then pop the stack and perform operations at that time.

if tail_op in rate1:
    if now_op in rate2 or now_op in rate3:
        return -1
    else:
        return 1

elif tail_op in rate2:
    if now_op in rate3:
        return -1
    else:
        return 1

Case 2: For the parentheses "(" on the top of the stack, if "(" encounters ")", you need to pop up "(" and discard ")"; if "(" encounters other operators, then All are pushed to the stack. "(" can meet ")", which means that the operators in the middle have been processed, and because the parentheses have no actual operation meaning, they can be discarded directly.

elif tail_op in rate3:
    if now_op in rate4:
        return 0   # (遇上)时,需要弹出(,且丢掉)
    else:
        return -1  # 栈顶元素为(时,只要当前元素不是)都应入栈

Case 3: If the top of the stack is a parenthesis ")", the current operator is pushed onto the stack.

else:
    return -1


entire code

def decision(tail_op, now_op):
    rate1 = ['+', '-']
    rate2 = ['*', '/']
    rate3 = ['(']
    rate4 = [')']

    if tail_op in rate1:
        if now_op in rate2 or now_op in rate3:
            return -1
        else:
            return 1

    elif tail_op in rate2:
        if now_op in rate3:
            return -1
        else:
            return 1
 
    elif tail_op in rate3:
        if now_op in rate4:
            return 0
        else:
            return -1

    else:
        return -1

Guess you like

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