在Python中,楊輝三角總是拿出來當演算法題考,那什么是楊輝三角呢?查看定義
先來觀察下面的楊輝三角圖例:

通過觀察會發現,楊輝三角的每行的第一個與最后一個數都是1,且從第3行開始非1數字是它左上方和右上方的數的和 !
那么知道了規律就可以開始寫代碼了
def triangles(row):
count = 0
while count < row:
arr = []
for i in range(count+1):
if i > 0 and i < count:
arr.append(lastList[i-1] + lastList[i])
else:
arr.append(1)
lastList = arr
yield arr
count += 1
for t in triangles(10):
print(t)
上面代碼寫完了,看著這么多代碼,那么是不是可以把代碼簡化一些呢?
然后就有了下面代碼
def triangles(row):
count = 0
while count < row:
arr = [arr[i-1] + arr[i] if i > 0 and i < count else 1 for i in range(count+1)]
yield arr
count += 1
for t in triangles(10):
print(t)
這樣代碼就簡潔很多了
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/123875.html
標籤:其他
上一篇:助力5G通信建設,由力自動化激光焊錫機在光模塊的應用
下一篇:Python基本資料型別
