生成器输出杨辉三角列表

烂漫一生 提交于 2020-02-10 19:45:26

2020-02-10 18:54:06

杨辉三角定义如下:

          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     i=1
 3     list1=[1]
 4     yield list1
 5     i=2
 6     list2=[1,1]
 7     yield list2
 8     list1=list2
 9     while i<=10:
10         i+=1
11         list2=[0 for i in range(0,i)]
12         list2[0]=1
13         list2[-1]=1
14         for j in range(1,i-1):
15             list2[j]=list1[j-1]+list1[j]
16         list1=list2
17         yield list2
18     

 

测试代码

 1 # 期待输出:
 2 # [1]
 3 # [1, 1]
 4 # [1, 2, 1]
 5 # [1, 3, 3, 1]
 6 # [1, 4, 6, 4, 1]
 7 # [1, 5, 10, 10, 5, 1]
 8 # [1, 6, 15, 20, 15, 6, 1]
 9 # [1, 7, 21, 35, 35, 21, 7, 1]
10 # [1, 8, 28, 56, 70, 56, 28, 8, 1]
11 # [1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
12 n = 0
13 results = []
14 for t in triangles():
15     results.append(t)
16     n = n + 1
17     if n == 10:
18         break
19 
20 for t in results:
21     print(t)
22 
23 if results == [
24     [1],
25     [1, 1],
26     [1, 2, 1],
27     [1, 3, 3, 1],
28     [1, 4, 6, 4, 1],
29     [1, 5, 10, 10, 5, 1],
30     [1, 6, 15, 20, 15, 6, 1],
31     [1, 7, 21, 35, 35, 21, 7, 1],
32     [1, 8, 28, 56, 70, 56, 28, 8, 1],
33     [1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
34 ]:
35     print('测试通过!')
36 else:
37     print('测试失败!')

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!