云腾软件

祥云工作室 QQ:252895542

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

列表生成:

L = [i for i in range(10)]

列表生成器:

g = (i for i in range(10))

函数生成器使用的关键字yield实现

例如fib生成器

  1 def fib(max):
  2     n, a, b = 0, 0, 1
  3     while n < max:
  4 	#print(b)
  5         yield b
  6         a, b = b, a + b
  7         n = n + 1
  8     return 'done'
View Code

杨辉三角定义如下:

          1
         / \
        1   1
       / \ / \
      1   2   1
     / \ / \ / \
    1   3   3   1
   / \ / \ / \ / \
  1   4   6   4   1
 / \ / \ / \ / \ / \
1   5   10  10  5   1
把每一行看做一个list,试写一个generator,不断输出下一行的list:
  1 def triangles():
  2     n = 0
  3     L1 = [1]
  4     L2 = [1, 1]
  5     L = []
  6     while True:
  7         n += 1
  8         if n == 1:
  9             L = L1
 10         elif n == 2:
 11             L = L2
 12         yield L
 13         L = [L[i] + L[i+1] for i in range(len(L) - 1)]
 14         L.insert(0, 1)
 15         L.append(1)
 16 
 17 n = 0
 18 results = []
 19 for t in triangles():
 20     print(t)
 21     results.append(t)
 22     n = n + 1
 23     if n == 10:
 24         break
 25 
 26 if results == [
 27     [1],
 28     [1, 1],
 29     [1, 2, 1],
 30     [1, 3, 3, 1],
 31     [1, 4, 6, 4, 1],
 32     [1, 5, 10, 10, 5, 1],
 33     [1, 6, 15, 20, 15, 6, 1],
 34     [1, 7, 21, 35, 35, 21, 7, 1],
 35     [1, 8, 28, 56, 70, 56, 28, 8, 1],
 36     [1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
 37 ]:
 38     print('测试通过!')
 39 else:
 40     print('测试失败!')
View Code
posted on 2018-04-19 10:06  云腾  阅读(589)  评论(1编辑  收藏  举报