Evaluation of four Operational expressions in [Python]


Evaluation of four Operational expressions

Train of thought

Using dual stack to achieve — the stack of valuesnumsStack and operatorops.

Algorithm steps
  1. For the original expression stringexpPreprocess it to a list of elements corresponding to a number or operatorexplist.
  2. ergodicexplistEach element is pushed into the corresponding stack in turn. After each push, it is judged whether the top two stacks can be multiplied and divided. The necessary and sufficient conditions for the top of stack to perform multiplication and division are as follows,opsThe top of the stack is one of < * >, < / > andnumsElement ratio inopsIf it is possible to operate, the operation is performed and the result is pushed backnumsMedium
  3. explistAfter traversing, all multiplication and division operations have been performedopsOnly addition and subtraction are left in. Next, another cycle is started, and the operation can be continuednumsThe only remaining element in is the value of the expression
def operation(a, b, op: str):
    Calculate the result of an operation
    :param a: val
    :param b: val
    : param OP: operator
    :return: val
    if op == '+':
        return a+b
    elif op == '-':
        return a-b
    elif op == '*':
        return a*b
    elif op == '/':
        return a/b
        Raise exception ('incorrect operator ')

def exp_str2list(exp: str):
    Set the expression exp:str Each element corresponds to a number < num > or operator < OP >
    Exp is known as a standard string of four arithmetic expressions
    : param exp: STR, expression
    :return: list
    Opset = {'+', '-', '*', '/'} operator set
    flag = -1
    explist = list()
    For I, char in enumerate (EXP): for each character in the expression string
        If char in opset: if char is an operator
            explist.append (Exp [Flag + 1: I]) from the previous operator to the current operator is a number, which is saved to explist
            Flag = I ා update flag to current OP position
            explist.append (char) ා the current OP is also added to explist
    return explist

def calculate_expression(exp: str):
    Evaluates the expression represented by the string exp and returns a numeric value
        Exp is known to be a standard string of four arithmetic expressions without parentheses
    : param exp: STR, expression
    :return: val
    opset = {'+', '-', '*', '/'}
    Nums = list(), number stack
    Ops = list() ා operator stack
    explist = exp_str2list(exp)
    for e in explist:
        #E stack
        If e in opset: ා if e is an operator
        #If e is a multiplication and division method with high priority, and
        #Nums and OPS match exactly, the top of the stack can be calculated once, and the result is pushed back to nums
        if ops and ops[-1] in {'*', '/'} and len(nums) == len(ops) + 1:
            op = ops.pop()
            y = nums.pop()
            x = nums.pop()
            nums.append(operation(x, y, op))
    #At this time, all the elements in explist have been traversed, and the multiplication and division methods have been operated, and only addition and subtraction are left to be operated on the double stack. As we all know, the addition and subtraction method obeys the combination law and can be calculated all the way
    while ops:
        op = ops.pop()
        y = nums.pop()
        x = nums.pop()
        x_op_y = operation(x, y, op)

    return nums[0]

if __name__ == '__main__':
    exp = '1*43+542+532*432'

reference material

  1. CSDN: expression evaluation — Python Dafa is good!https://blog.csdn.net/Hpuer_R…