Home Backend Development Python Tutorial Introduction to the usage of recursive calls of python generators (code example)

Introduction to the usage of recursive calls of python generators (code example)

Nov 24, 2018 pm 04:05 PM

This article brings you an introduction to the usage of recursive calls of Python generators (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Generator

What is a generator: As long as the yield keyword appears in the function body, then the function code will not be executed when the function is executed, and a result will be obtained. The result is the generator

The generator is the iterator

The function of yield

yield provides us with a way to customize the iterator object

## The difference between #yield and return:

1. Yield can return multiple values ​​

2. The pause and resumption of functions are saved by yield for us

As long as you see the function If yield appears in it, then it is a generator

Example 1: As we mentioned above, if we see yield in the function, then it is a generator, and the generator is an iterator,

Then when it comes to iteration The processor should think of the value method of xx.__next__()

def test():
    print('=====>1')
    yield 1
    print('=====>2')
    yield 2
    print('=====>3')
    yield 3
g = test()  #就相当于一个容器
print(g.__next__())
print(g.__next__())
print(next(g))
Copy after login

Running result:

We After knowing this way to obtain values, you will think of another simple way with the same principle is the for loop

def test():
    print('=====>1')
    yield 1
    print('=====>2')
    yield 2
    print('=====>3')
    yield 3
g = test()
for i in g:
    print(i)
Copy after login

Running result:

Example 2: To call the result of test1 to test2, you need to use yield to customize a generator

def test1():
    for i in range(10):
        yield i   #把0~9变成生成器返回给函数test1
g = test1()     #g是个生成器
def test2(g):
    for i in g:
        print(i)
test2(g)
Copy after login

Running results:

Example 3: Log error monitor

import time
def tail(filepath):   #定义一个查看文件的函数
    with open(filepath, 'rb') as f:   #打开形参为filepath rb是二进制读
        f.seek(0,2)    #把光标移动到末尾
        while True:  #循环监控日志
            data = f.readline()   #读取文件末尾
            if data:   #加入有数据就用yield返回
                yield data
            else:#  否则就睡眠0.05秒
                time.sleep(0.05)
def grep(file, k):    #定义过滤关键字函数
    for i in tail(file):   #循环生成器中的数据
        if k in i.decode('utf-8'):  #因为是用二进制读取方式,所以需要解码显示
            print(i.decode('utf-8'))
grep('a.txt', '500')  #监控a.txt最新日志,并过滤500的错误代码
Copy after login

Once 500 appears, it will be captured

## Another usage of yield, assign value

def test(name):
    while True:
        foot = yield
        print('%s正在吃%s' % (name, foot))

e = test('轩轩') #e是生成器
next(e)    #初始化,e.__next__()
# e.send(None)    #初始化,与上一行二选一
e.send('饺子')    #发送值传给foot
e.send('冰激凌')    #发送值传给foot
Copy after login

Run result:

##Recursive call

Recursive call:

In the process of calling a function, the function itself is called directly or indirectly, which is called recursive callThe two necessary stages of recursion:

1 recursion, 2 backtracking

Example: A, B, C, D, and E, 5 people eat buns. We want to know how many buns A ate, but A said it was better than B. Eat 2 more pieces. B said he ate 2 more pieces than C. C said he ate 2 more pieces than D. Ding said he ate 2 more pieces than E. E said he didn't eat it.

Then because he knew that E didn't eat it , so according to the answers of A, B, C and D, we know that A ate 8, so the process of going back and forth is recursion and backtracking

age(A) = age(B) 2

age(B) = age(C) 2

age(C) = age(D) 2

age(D) = age(E) 2

age( E) = 0

def num(n):    
if n == 1:        
return 0    
return num(n-1) + 2res = num(5) 
print(res)
Copy after login

Run result:

The above is the detailed content of Introduction to the usage of recursive calls of python generators (code example). 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

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 to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

What are regular expressions? What are regular expressions? Mar 20, 2025 pm 06:25 PM

Regular expressions are powerful tools for pattern matching and text manipulation in programming, enhancing efficiency in text processing across various applications.

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

What are some popular Python libraries and their uses? What are some popular Python libraries and their uses? Mar 21, 2025 pm 06:46 PM

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

How to dynamically create an object through a string and call its methods in Python? How to dynamically create an object through a string and call its methods in Python? Apr 01, 2025 pm 11:18 PM

In Python, how to dynamically create an object through a string and call its methods? This is a common programming requirement, especially if it needs to be configured or run...

See all articles