Skip to content

Instantly share code, notes, and snippets.

@booxood
Last active December 22, 2015 12:28
Show Gist options
  • Save booxood/6472345 to your computer and use it in GitHub Desktop.
Save booxood/6472345 to your computer and use it in GitHub Desktop.
python yield Fibonacci
#返回一个list
#如果list很大,会占用很多内存
def fab(max):
f = []
n, a, b = 0, 0, 1
while n < max:
f.append(b)
a, b = b, a+b
n += 1
return f
#构造一个支持iterablie的class
class Fab(object):
def __init__(self, max):
self.max = max
self.a, self,b ,self.n = 0, 1, 0
def __iter__(self):
return self
def next(self):
if self.n < self.max:
t = self.b
self.a, self.b = self.b, self.a + self.b
self.n += 1
return t
raise StopIteration()
#函数使用yield后,会返回一个generator
#当你调用这个函数的时候,函数内部的代码并不立马执行 ,这个函数只是返回一个生成器对象,
#第一次迭代时函数会从开始执行到达 yield 关键字,然后返回 yield 后的值作为第一次迭代的返回值.
#然后,下一次迭代时是从上一次暂停的地方(yield后)继续往后执行,到达yield关键字后再返回那个值,直到没有可以返回的。
def fab(max):
n, a, b = 0, 0, 1
while n < max:
yield b
a, b = b, a+b
n += 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment