python3練習-楊輝三角/帕斯卡三角形


楊輝三角形式如下:
1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 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 = 0
for 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=0
for 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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM