时间:2021-07-01 10:21:17 帮助过:21人阅读
yield 的好处:把一个函数改写为一个 generator 就获得了迭代能力,比起用类的实例保存状态来计算下一个 next() 的值,不仅代码简洁,而且执行流程异常清晰。
测试代码:
def fab(max):
"""斐波那契數列"""
n, a, b = 0, 0, 1
while n < max:
yield b
a, b = b, a + b
n += 1
def perm(items, n=None):
"""全排列"""
if n is None:
n = len(items)
for i in range(len(items)):
v = items[i:i+1]
if n == 1:
yield v
else:
rest = items[:i] + items[i+1:]
for p in perm(rest, n-1):
yield v + p
if __name__ == '__main__':
for n in fab(5):
print n
print "全排列:123"
for n in perm("123"):
print n