Python yield summary and instances

  • 2020-04-02 13:35:53
  • OfStack

A function with yield is an generator. Unlike normal functions, an generator looks like a function call, but does not execute any function code until it is called next() (which is automatically called next() in the for loop). Although the execution flow continues as the function's flow, each execution to a yield statement breaks, returns an iteration, and continues from the next yield statement at the next execution. It looks as if a function is interrupted by yield several times during normal execution, with each interrupt returning the current iteration value via yield.

The benefits of yield: Writing a function to a generator gives you the ability to iterate, which is much cleaner than using an instance of the class to save state to calculate the value of the next next().

Test code:
 


#!/usr/bin/env python
#-*- coding:utf8 -*-
def fab(max):
    """ Fibonacci """
    n, a, b = 0, 0, 1
    while n < max:
        yield b
        a, b = b, a + b
        n += 1

def perm(items, n=None):
    """ The whole arrangement """
    if n is None:
        n = len(items)
    for i in range(len(items)):
        v = items[i:i+1]
        if n == 1:
            yield v
        else:
            rest = items[:i] + items[i+1:]
            for p in perm(rest, n-1):
                yield v + p
if __name__ == '__main__':
    for n in fab(5):
        print n
    print  " The whole arrangement :123"
    for n in perm("123"):
        print n


Related articles: