Python yield Summary and instance _python

Source: Internet
Author: User

A function with yield is a generator, unlike a normal function, which generates a generator that 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, to begin execution. Although the execution process is still executed as a function's process, each execution to a yield statement is interrupted and an iteration value is returned, and the next execution is performed from the next statement of yield. It looks as if a function was interrupted several times by yield during normal execution, with each interrupt returning the current iteration value through yield.

the benefit of yield: rewriting a function as a generator gives you the ability to iterate over the value of the next next () rather than the instance save state of the class, not only the code is concise, but the execution process is unusually clear.

Test code:

Copy Code code as follows:

#!/usr/bin/env python
#-*-Coding:utf8-*-

Def FAB (max):
"" "" Fibonacci Number Column ""
N, a, b = 0, 0, 1
While n < max:
Yield b
A, B = B, A + b
n + 1


def perm (items, N=none):
    "" All-Arrange ""
    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 "All: 123"
For N in Perm ("123"):
Print n

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.