full-speed-python习题解答(七)--生成器

迭代器(iterator)是经常与for循环一起使用的可迭代对象(iterable)。Python中的生成器(generator)是实现迭代器的一种方便方法。生成器不是class,而是使用yield关键字作返回值的函数。

1. Implement a generator called “squares” to yield the square of all numbers from (a)
to (b). Test it with a “for” loop and print each of the yielded values.

def squares(a,b):
    while a<=b:
        yield a*a
        a+=1

for i in squares(1,5):
    print(i)

2. Create a generator to yield all the even numbers from 1 to (n).

def even(n):
    a=1
    while a<n:
        yield a+1 
        a+=2
    
for i in even(6):
    print(i)

3. Create another generator to yield all the odd numbers from 1 to (n).

def odd(n):
    a=1
    while a<=n:
        yield a
        a+=2

for i in odd(10):
    print(i)

4. Implement a generator that returns all numbers from (n) down to 0.

def odd(n):
    while n>=0:
        yield n
        n-=1
for i in odd(10):
    print(i)

5. Create a generator to return the fibonnaci sequence starting from the first element
up to (n). The first numbers of the sequence are: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55,
89, . . .

def fibonnaci(n):
    curr=0
    flo=1
    i=0
    while i<n:
        value=curr
        yield value
        curr=flo
        flo+=value
        i+=1
    
for i in fibonnaci(12):
    print(i)

6. Implement a generator that returns all consecutive pairs of numbers from 0 to (n),
such as (0, 1), (1, 2), (2, 3). . .

def consecutive_pairs(n):
    a=0
    while a<n:
        yield (a,a+1)
        a+=1

for i in consecutive_pairs(10):
    print(i)

猜你喜欢

转载自blog.csdn.net/qq_33251995/article/details/85259243
今日推荐