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)


版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

评论