简体   繁体   中英

Python yield keyword significance and confusion about generators?

I am confused why didnt we say yield b and what will the differenccce be if i removed yield a ?

I am just confused on how they compare to a normal function?

def fibonacci(n):
    """ A generator for creating the Fibonacci numbers """
    a, b, counter = 0, 1, 0
    while True:
        if (counter > n): 
            return
        yield a
        a, b = b, a + b
        counter += 1
f = fibonacci(5)
for x in f:
    print(x, " ", end="") # 
print()

The normal function would look nearly the same:

def fibonacci(n):
    """ A  for creating the Fibonacci numbers """
    a, b, counter = 0, 1, 0
    
    while True:
        if (counter > n): 
            
        
        a, b = b, a + b
        counter += 1

b is only used to track the internal state of the process. a is the only value ever directly exposed via the iterator or the return value, and b is only used to compute a .

The regular function computes all the requested Fibonacci numbers, then stores them in a list and returns that list to the caller. This may require significant time and memory if n is large.

The generator function, on the other hand, returns almost immediately, because it hasn't computed anything yet. It has only returned a generator instance, which will, when passed to next , compute the next Fibonacci number in the sequence and return it, then go back to waiting until you call next again. It only ever uses a small, constant amount of memory, and each call to next only takes as much time as is needed to perform a handful of additions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM