Four in-depth parsing operations

Source: Internet
Author: User
This article is mainly intended for in-depth analysis of the four arithmetic operations, which has a certain reference value. interested friends can refer to how to calculate the string arithmetic expression?

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) infix expression from right to left scan

(3) press the operand into S2.

(4) when an operator is encountered, compare its priority with the S1 stack top operator:

(4-1) If S1 is null, or the top-end operator of the stack is ")", the operator is directly added to the stack.

(4-2) Otherwise, if the priority is higher or equal than that of the top-stack operator, the operator is also pushed to S1.

(4-3) Otherwise, the operator at the top of the S1 stack is pushed to S2,

Go to (4-1) again to compare with the new stack top operator in S1

(5) parentheses:

(5-1) if it is ")", Press S1 directly.

(5-2) if it is a left brace "(", the operator at the top of the S1 stack is popped up and pushed to S2 until the right brace is encountered,

Discard this pair of parentheses.

(6) repeat steps (2) to (5) until the leftmost part of the expression.

(7) pop up the remaining operators in S1 and press them into S2.

(8) the elements in S2 are displayed and output 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

The above is the details of the four in-depth parsing operations. For more information, see other related articles in the first PHP community!

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.