Python应用集python效率rua

Python yield

2019-01-17  本文已影响0人  Solomon_Xie

参考:Python yield 使用浅析 - IBM

def fab(max): 
    n, a, b = 0, 0, 1 
    while n < max: 
        yield b
        a, b = b, a + b 
        n = n + 1 

for n in fab(5): 
    print n 

递归中使用yield

有时候yield就可以解决递归的问题,但是有时候解决不了,还是要用递归。然后递归的同时还想达到yield的效果,就需要动点脑子了。

参考:Recursion using yield

def recursion(self, num):
    result = num**2
    yield result
    if num < 100:
        yield from self.recursion(result)

for rec in recursion(100):
    print( rec )
上一篇下一篇

猜你喜欢

热点阅读