• 生成器输出杨辉三角列表


    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('测试失败!')
    追风少年
  • 相关阅读:
    poj 3378 Crazy Thairs 夜
    1487. Chinese Football 夜
    容斥原理
    Dancing Links
    三角剖分
    模线性方程模板
    模线性方程
    容斥原理 POJ2773
    DNA Sequence [矩阵]
    hdu 2588 容斥
  • 原文地址:https://www.cnblogs.com/lzycodinglife/p/12292154.html
Copyright © 2020-2023  润新知