Python之杨辉三角算法实现

时间:2023-03-09 15:26:42
Python之杨辉三角算法实现

学习了廖雪峰的官方网站的python一些基础,里面有个题目,就是让写出杨辉三角的实现,然后我就花了时间实现了一把。思路也很简单,就是收尾插入0,然后逐层按照杨辉三角的算法去求和实现杨辉三角。

Python之杨辉三角算法实现

附属代码:

 # -*- coding: utf-8 -*-

 # 期待输出:
# [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] def triangles(): L = [1]
yield L
while True:
# print 'L是:',L # 在L这个List头尾插入0
L.insert(0,0)
L.insert(len(L),0) n = 0
# print 'n:%d--L的长度%d'%(n,len(L))
T = []
while n < len(L)-1:
T.append(L[n]+L[n+1])
n = n+1 L = T
yield L n = 0
for t in triangles():
print(t)
n = n + 1
if n == 10:
break