Resolution of four arithmetic operations and four arithmetic operations

Source: Internet
Author: User

Resolution of four arithmetic operations and four arithmetic operations

How can I calculate the arithmetic expression of a string?

If regular expressions are used for matching, it is a bit difficult to think about, and the general idea is to design recursion. in Python, recursion is not recommended,

Because it not only has a limit on Recursive depth (generally 1000 stack frames), but also does not support tail recursive optimization.

 

The simplest way is to convert the expression into a prefix expression and then calculate the result through the prefix expression.

Prefix expressions (before operators) are also called Polish expressions, and the corresponding suffix expressions (after operators) are also called inverse Polish expressions.

Most common programming languages use infix expressions.

 

Rules for converting an infix expression to a prefix expression:

(1) initialize two stacks: Operator stack S1 and stack S2 that stores intermediate results; (2) scan the infix expression from right to left (3) When an operand is encountered, press it into S2 (4) and compare it with the priority of the S1 stack top operator when it encounters an operator: (4-1) If S1 is blank, or the stack top operator is right brace ") ", this operator is directly written into the stack (4-2). Otherwise, if the priority is higher or equal than the top of the stack operator, the operator is also pushed to S1 (4-3). Otherwise, the operator at the top of the S1 stack pops up and is pushed to S2, and then switched to (4-1) Again. Compared with the operator at the top of the stack in S1 (5), when parentheses are encountered: (5-1) if it is a right brace ")", Press S1 (5-2) if it is a left brace "(", the operator at the top of the S1 stack is displayed in sequence, press S2 until the right parenthesis is encountered. In this case, discard the pair of parentheses (6) and Repeat steps (2) to (5) until the leftmost side (7) of the expression) the remaining operators in S1 are pushed out in sequence and elements in S2 (8) are pushed out in sequence. The result is the prefix expression corresponding to the infix expression.

The biggest feature of prefix expression calculation is that it removes brackets.

 

Convert an infix expression to a prefix expression

Def mid_to_prev (expressions: str): priority = {# Operator priority "/": 1, "//": 1, "*": 1, "%": 1, "+": 0, "-": 0, "**": 2} expression_list = expressions. split () # number_stack = [] # digital stack symbol_stack = [] # Operator stack for x in expression_list [:-1]: if x. isdigit (): number_stack.insert (0, x) # else: if x = '(': # If yes (the operator in the operator stack is popped up until it is encountered (pop_symbol = symbol_stack [0] while pop_symbol! = ')': Pop_symbol = symbol_stack.pop (0) number_stack.insert (0, pop_symbol) pop_symbol = symbol_stack [0] else: symbol_stack.pop (0) elif len (symbol_stack) = 0 or symbol_stack [0] = ')' or x = ')' or priority [x]> = priority [symbol_stack [0]: symbol_stack.insert (0, x) # When the symbol stack is empty or encounters) or the symbol at the top of the stack is) or an operator with a higher priority than or equal to the top of the symbol stack can be directly stored in elif priority [x] <priority [symbol_stack [0]: # while symbol_sta has a lower priority than the top element of the symbol Stack Ck [0]! = ')' And priority [x] <priority [symbol_stack [0]: number_stack.insert (0, symbol_stack.pop (0) else: symbol_stack.insert (0, x) else: while len (symbol_stack )! = 0: number_stack.insert (0, symbol_stack.pop (0) return number_stack

Example:

It is easy to calculate the converted prefix expression stack.

(1) initialize a new list

(2) traverse the prefix expression list from right to left. When a number is encountered, it is saved to the new list.

(3) When an operator is encountered, the first two digits in the new list are displayed for calculation, and the result is saved to the new list.

(4) Until the prefix expression list is traversed in the new list, there is only one element in the new list, which is the final result.

Def calc (number1, number2, calc): # two numeric operations if calc = '/': return number1/number2 elif calc = '*': return number1 * number2 elif calc = '//': return number1 // number2 elif calc = '**': return number1 ** number2 elif calc = '% ': return number1 % number2 elif calc = '+': return number1 + number2 elif calc = '-': return number1-number2

Get the overall result:

def operation(stack_list:list):    number = []    for x in stack_list[::-1]:        if x.isdigit():            number.insert(0, x)        else:            first = number.pop(0)            second = number.pop(0)            tmp = calc(int(first),int(second), x)            number.insert(0,tmp)    return number.pop(0)

Instance:

Prefix expression result:

The verification result is correct.

 

Note: expressions must be separated by spaces.

Only matching the integer

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.