Generator Simple Introduction

Source: Internet
Author: User
Tags function definition generator stdin

Questions raised:
We know that through the list generation, we can create a list directly. However, the list capacity is certainly limited by the memory limit. And, creating a list of 1 million elements, not only takes up a lot of storage space, but if we just need to access the first few elements, the space behind most of the elements is wasted.
So if the list element can be calculated according to some algorithm, then whether we can continue to calculate the subsequent elements in the process of the loop. This eliminates the need to create a complete list, which saves a lot of space.
Build Device
in Python, this loop-side computing mechanism is called the Generator (generator).
There are a number of ways to create a generator. The first method is simple, as long as you change a list-generated [] to (), you create a generator:

>>> L = [x * x for x in range (Ten)]
>>> L
[0, 1, 4, 9,,, BA]
>>> g = (x * x for x in range (a))
>>> g
<generator object <genexpr> at 0x104feab40>

The difference between creating L and G is only the outermost [] and (), L is a list, and G is a generator.

We can print out every element of the list directly, but how do we print out every element of the generator.
If you want to print one, you can pass the generator Next () method:

>>> G.next () 0
>>> g.next () 1
>>> G.next () 4
>>> G.next () 9
> >> g.next ()
>>> g.next ()
>>> g.next ()
>>> g.next ()
> >> g.next ()
>>> g.next () Bayi
>>> g.next () traceback (most recent call last):
  File "<stdin>", line 1, in <module>stopiteration

generator Saves the algorithm , and each time you call next, the value of the next element is computed until the last element is computed, and no more elements are thrown when the stopiteration error is raised.

Learning generators through the Fibonacci Buraki series

The famous Fibonacci sequence (Fibonacci), with the addition of the first and second numbers, any number can be added together by the first two numbers:
1, 1, 2, 3, 5, 8, 13, 21, 34, ...
The Fibonacci sequence is not written in list generation, but it's easy to print it out with a function:

def fib (max):
    N, a, b = 0, 0, 1 while
    n < max:
        print B
        A, B = B, a + b
        n = n + 1

Careful observation, we can see that the FIB function is actually defined the Fibonacci sequence of the calculation rules, you can start from the first element to calculate the subsequent arbitrary elements, this logic is very similar to generator.
In other words, the above function and generator are only one step away. to turn the FIB function into a generator, you simply change print B to yield B :

def fib (max):
    N, a, b = 0, 0, 1 while
    n < max:
        yield b
        A, B = B, a + b
        n = n + 1

This is another way to define generator . If a function definition contains the yield keyword , then the function is no longer a normal function, but a generator:

>>> fib (6) <generator object fib at 0x104feaaa0>

The most difficult thing to understand here is that the generator and function are not performing the same process. The function is executed sequentially, and the return statement is encountered or the last line of function statement is returned. The function that becomes generator, executes at each call next (), encounters a yield statement return, and executes again from the last yield statement that was returned.
To give a simple example, define a generator, and then return the number 1,3,5:

>>> def Odd ():
.     Yield 1 ...     print ' Step 2 '
...     Yield 3 ...     print ' Step 3 '
...     Yield 5 ...
>>> o = Odd ()
>>> o.next () step
>>> o.next () step
>> > O.next () step
>>> o.next ()
Traceback (most recent called last):
  File "<stdin> ", line 1, in <module>
stopiteration

As you can see, odd is not a normal function, but a generator, in the execution process, encountered yield interrupted, the next time to continue execution. After performing 3 yield, no yield can be executed, so the 4th call to Next () is an error.
Back to Fib's example, we constantly call yield during the loop, and we interrupt. Of course, set a condition to the loop to exit the loop, or it will produce an infinite series out.
Again, after changing the function to generator, we basically never invoke it with next (), but instead use the For loop to iterate:

>>> for N in fib (6):
    print n
1
1
2
3
5
8

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.