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)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值