首页 > 代码库 > python3练习-杨辉三角/帕斯卡三角形

python3练习-杨辉三角/帕斯卡三角形

杨辉三角形式如下:
1 1 1 1 2 1 1 3 3 1 1 4 6 4 11 5 10 10 5 1
# 期待输出:# [1]# [1, 1]# [1, 2, 1]# [1, 3, 3, 1]# [1, 4, 6, 4, 1]# [1, 5, 10, 10, 5, 1]# [1, 6, 15, 20, 15, 6, 1]# [1, 7, 21, 35, 35, 21, 7, 1]# [1, 8, 28, 56, 70, 56, 28, 8, 1]# [1, 9, 36, 84, 126, 126, 84, 36, 9, 1]n = 0for t in triangles():    print(t)    n = n + 1    if n == 10:        break
思路:1、第i-1行最后补0,将长度与第i行保持一致;2、第i行第n个元素值为L(i)[n] = L(i-1)[n-1]+L(i-1)[n]例如:1、i=3时,此时集合为[1,3,3,1];2、i-1行集合补0后,集合为[1,2,1,0]3、L(3)[0]=L(2)[-1]+L(2)[0]=0+1=1     L(3)[1]=L(2)[0]+L(2)[1]=1+2=3     .....
代码如下:def triangles():    L = [1]    while True:        yield L        L.append(0)        L = [L[i - 1] + L[i] for i in range(len(L))]n=0for t in triangles():    print(t)    n = n + 1    if n == 10:        break

 

python3中,list[-1]表示为list集合中的最后一个元素

其他相关:

此练习源于学习python过程中的笔记。

学习网站来源于廖雪峰的官方网站:http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000

相关章节链接:

http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0014317799226173f45ce40636141b6abc8424e12b5fb27000

python3练习-杨辉三角/帕斯卡三角形