Home Backend Development Python Tutorial In-depth analysis of the four arithmetic operations

In-depth analysis of the four arithmetic operations

Mar 26, 2017 pm 04:50 PM
Arithmetic

How to calculate the arithmetic expression of a string?

If you use regular expression to match, it is a bit unthinkable, and the general idea is to recursion, but in Python it is It is highly not recommended to use recursion,

because it not only has a limit on the recursion depth (usually 1000 stack frames), but also does not support tail recursion optimization.

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

The prefix expression (in front of operator ) is also called Polish expression, and the corresponding suffix expression (in the back of operator) is also called reverse Polish expression, and in our lives , and

Commonly used in most programming languages are infix expressions.

Rules for converting infix expressions into prefix expressions:

 (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 the operand is encountered, push it into S2

. (4) When the operator is encountered, compare it with S1. The priority of the operator on the top of the stack:

 (4-1) If S1 is empty, or the operator on the top of the stack is a right bracket ")", push this operator directly onto the stack

 (4-2) Otherwise, if the priority is higher or equal to the operator on the top of the stack, push the operator into S1

 (4-3) Otherwise, push S1 onto the stack The top operator is popped and pushed into S2,

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

(5) When encountering parentheses :

 (5-1) If it is a right bracket ")", push S1

directly. (5-2) If it is a left bracket "(", pop up the top of S1 stack one by one operator, and push S2 until the right bracket is encountered,

At this time, discard this pair of brackets

(6) Repeat steps (2) to (5) until The leftmost

of the expression (7) Pop the remaining operators in S1 one by one and push them into S2

 (8) Pop the elements in S2 one by one and output them, the result is the infix The prefix expression corresponding to the expression.

The biggest feature of using prefix expressions is that it removes the parentheses

Convert the infix expression into a prefix expression

def mid_to_prev(expressions: str):
    priority = {  # 运算符的优先级
        "/": 1,
        "//": 1,
        "*": 1,
        "%": 1,
        "+": 0,
        "-": 0,
        "**": 2 }
    expression_list = expressions.split() # 
    number_stack = [] # 数字栈
    symbol_stack = [] # 运算符栈
    for x in expression_list[::-1]:
        if x.isdigit():             
            number_stack.insert(0, x)  # 如果是整数直接存进去
        else:
            if x == '(':         # 如果是 ( 弹出运算符栈中的运算符直到遇到 ( 
                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)  # 当符号栈为空 或者 遇到 ) 或者栈顶的符号是 ) 或者优先级大于等于符号栈顶的运算符优先级 直接存进去

            elif priority[x] < priority[symbol_stack[0]]:  # 优先级小于符号栈顶元素的时候
                while symbol_stack[0] != &#39;)&#39; 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
Copy after login
##. #Example:

In-depth analysis of the four arithmetic operationsIt is simple to operate the converted prefix expression stack

(1)Initialize a new list

(2) Traverse the prefix expression list from right to left. When encountering a number, store it in a new list

(3) When encountering an operator, pop up the first two numbers in the new list and perform operations. Then save the result 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): # 两个数运算
    if calc == &#39;/&#39;:
        return number1 / number2
    elif calc == &#39;*&#39;:
        return number1 * number2
    elif calc == &#39;//&#39;:
        return number1 // number2
    elif calc == &#39;**&#39;:
        return number1 ** number2
    elif calc == &#39;%&#39;:
        return number1 % number2
    elif calc == &#39;+&#39;:
        return number1 + number2
    elif calc == &#39;-&#39;:
        return number1 - number2
Copy after login

obtained Total 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)
Copy after login

Example:

Previous prefix expression result:

In-depth analysis of the four arithmetic operations

In-depth analysis of the four arithmetic operations The verified result is correct.

Note: The expression must be separated by spaces

Only integers are matched

The above is the detailed content of In-depth analysis of the four arithmetic operations. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How Go language implements four arithmetic operations How Go language implements four arithmetic operations Dec 21, 2023 pm 04:46 PM

In Go language, the four arithmetic operations are implemented through basic arithmetic operators. Four commonly used arithmetic operations: 1. Addition (+): used to add two numbers; 2. Subtraction (-): used to subtract the second number from the first number; 3. Multiplication (* ): used to multiply two numbers; 4. Division (/): used to divide the first number by the second number.

Four arithmetic operations library written in Go language: a simple and efficient mathematical calculation tool Four arithmetic operations library written in Go language: a simple and efficient mathematical calculation tool Dec 23, 2023 am 11:49 AM

Four arithmetic operations library written in Go language: simple and efficient mathematical calculation tools. With the continuous advancement of computer technology, mathematical calculations play an increasingly important role in our daily lives and work. Whether you are performing complex data analysis or simple data processing, mathematical calculations are an indispensable part. In order to improve calculation efficiency and accuracy, we need to rely on high-quality mathematical calculation tools. As a modern, high-performance programming language, Go language provides rich and powerful tools for performing mathematical operations. This article will introduce

Implement a basic arithmetic operator using Go language Implement a basic arithmetic operator using Go language Dec 23, 2023 pm 02:52 PM

The Go language is an open source, statically typed compiled language that has received widespread attention and use for its simplicity, efficiency, and easy expansion. This article will introduce how to use Go language to write a simple four-arithmetic calculator and provide specific code examples. First, we need to define several basic data structures to represent operational expressions and operators. We can use structures to represent operators and operands, and use enumeration types to limit the value range of operators. typeOperatorintcons

A simple introductory guide to the four arithmetic operations of Go language A simple introductory guide to the four arithmetic operations of Go language Feb 19, 2024 pm 12:18 PM

Getting Started Guide: Learn the steps to implement the four arithmetic operations of Go language from scratch. As a simple and efficient programming language, Go language is becoming more and more popular among programmers. It is not complicated to implement the four arithmetic operations in the Go language. This article will start from scratch and guide you step by step to learn how to implement the four arithmetic operations in the Go language. This article will include specific code examples to help you better understand how each step is implemented. Step 1: Create a new Go language project First, we need to create a new Go language project. Execute the following in the command line

Learn the principles and practices of the four arithmetic operations in Go language Learn the principles and practices of the four arithmetic operations in Go language Dec 23, 2023 pm 01:07 PM

Title: Learning the principles and practice of four arithmetic operations through Go language Introduction: Go language is a compiled, high-concurrency open source language that is simple, reliable, and efficient. Learning the principles and practices of the four arithmetic operations through the Go language can not only provide an in-depth understanding of basic mathematical operation rules, but also exercise programming thinking and skills. This article will introduce the basic principles of the four arithmetic operations, and write sample code in the Go language to demonstrate the practical process of the four arithmetic operations. 1. Basic principles of the four arithmetic operations The four arithmetic operations are the most basic operations in mathematics, including addition, subtraction, multiplication

Go language basic tutorial: Implementation methods of four arithmetic operations Go language basic tutorial: Implementation methods of four arithmetic operations Dec 23, 2023 am 09:00 AM

Go language basic tutorial: Implementation methods of the four arithmetic operations, requiring specific code examples Introduction: Go language, as a programming language for developing cloud native applications, is favored by more and more developers. As a beginner learning Go language, it is essential to master basic calculation operations. This article will introduce the basic methods of implementing four arithmetic operations in Go language and provide specific code examples. Addition operation Addition operation is one of the simplest arithmetic operations and we can use the plus sign (+) to represent the addition operation. Here is a sample code: packag

A quick introduction to learning Go language to implement four arithmetic operations A quick introduction to learning Go language to implement four arithmetic operations Feb 19, 2024 pm 02:59 PM

Quickly get started with the implementation of the four arithmetic operations in the Go language. When learning a new programming language, mastering the basic four arithmetic operations is a very important step. This article will briefly introduce the method of implementing four arithmetic operations in Go language and provide specific code examples. Go language is a concise and efficient programming language developed and promoted by Google. It contains a rich standard library and also has powerful features such as object-oriented and concurrent programming, making it suitable for various types of application development. The basic principle of implementing the four arithmetic operations is to use the basic principles of Go language

Powerful functions: Use Go language to implement four arithmetic operations to easily cope with complex operation requirements Powerful functions: Use Go language to implement four arithmetic operations to easily cope with complex operation requirements Feb 26, 2024 pm 02:36 PM

Title: Powerful functions: Use Go language to implement four arithmetic operations to easily cope with complex computing requirements. With the development of the computer field, the four arithmetic operations, as one of the most basic mathematical operations, are often widely used in various software development. In order to better meet complex computing needs, many developers use efficient programming languages ​​​​such as the Go language to implement related functions. This article will introduce how to use Go language to implement four arithmetic operations, from simple addition, subtraction, multiplication and division to complex operations that support parentheses and precedence, helping readers easily solve calculation problems. At first, we

See all articles