Skip to main content

Introducing generators

>>> def make_counter(x):
...     print 'entering make_counter'
...     while 1:
...         yield x
...         print 'incrementing x'
...         x = x + 1
...
>>> counter = make_counter(2)
>>> coutner
Traceback (most recent call last):
  File "", line 1, in
NameError: name 'coutner' is not defined
>>> counter

>>> counter.next()
entering make_counter
2
>>> counter.next()
incrementing x
3
>>> counter.next()
incrementing x
4


The presence of the yield keyword in make_counter means that this is not a normal function. It is a
special kind of function which generates values one at a time. You can think of it as a resumable function.
Calling it will return a generator that can be used to generate successive values of x.


To create an instance of the make_counter generator, just call it like any other function. Note that this does
not actually execute the function code. You can tell this because the first line of make_counter is a print
statement, but nothing has been printed yet.


The make_counter function returns a generator object.

The first time you call the next() method on the generator object, it executes the code in make_counter
up to the first yield statement, and then returns the value that was yielded. In this case, that will be 2, because
you originally created the generator by calling make_counter(2).


Repeatedly calling next() on the generator object resumes where you left off and continues until you hit the
next yield statement. The next line of code waiting to be executed is the print statement that prints
incrementing x, and then after that the x = x + 1 statement that actually increments it. Then you loop
through the while loop again, and the first thing you do is yield x, which returns the current value of x
(now 3).









Using generators instead of recursion
def fibonacci(max):
    a, b = 0, 1
    while a < max:
        yield a
        a, b = b, a+b

for n in fibonacci(100000):
    print n,





You can use a generator like fibonacci in a for loop directly. The for loop will create the generator
object and successively call the next() method to get values to assign to the for loop index variable (n).


Each time through the for loop, n gets a new value from the yield statement in fibonacci, and all you do
is print it out.



Comments

Popular posts from this blog

CKA Simulator Kubernetes 1.22

  https://killer.sh Pre Setup Once you've gained access to your terminal it might be wise to spend ~1 minute to setup your environment. You could set these: alias k = kubectl                         # will already be pre-configured export do = "--dry-run=client -o yaml"     # k get pod x $do export now = "--force --grace-period 0"   # k delete pod x $now Vim To make vim use 2 spaces for a tab edit ~/.vimrc to contain: set tabstop=2 set expandtab set shiftwidth=2 More setup suggestions are in the tips section .     Question 1 | Contexts Task weight: 1%   You have access to multiple clusters from your main terminal through kubectl contexts. Write all those context names into /opt/course/1/contexts . Next write a command to display the current context into /opt/course/1/context_default_kubectl.sh , the command should use kubectl . Finally write a second command doing the same thing into ...

OWASP Top 10 Threats and Mitigations Exam - Single Select

Last updated 4 Aug 11 Course Title: OWASP Top 10 Threats and Mitigation Exam Questions - Single Select 1) Which of the following consequences is most likely to occur due to an injection attack? Spoofing Cross-site request forgery Denial of service   Correct Insecure direct object references 2) Your application is created using a language that does not support a clear distinction between code and data. Which vulnerability is most likely to occur in your application? Injection   Correct Insecure direct object references Failure to restrict URL access Insufficient transport layer protection 3) Which of the following scenarios is most likely to cause an injection attack? Unvalidated input is embedded in an instruction stream.   Correct Unvalidated input can be distinguished from valid instructions. A Web application does not validate a client’s access to a resource. A Web action performs an operation on behalf of the user without checkin...