杨辉三角

来源:互联网 发布:科比安东尼西决数据 编辑:程序博客网 时间:2024/06/05 15:17

杨辉三角
[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]
代码分享:
方法1:每一行数据前后2项都是1,其它的数据是前一行相邻两数之和;
def yhsj():
s=[1]
while True:
yield s #生成器
s=[s[i]+s[i+1] for i in range(len(s)-1)]
s.insert(0,1)
s.append(1)
for i in yhsj():
print(i)
n=n+1
if n>10:
break
方法2:分析数据规律,
第1行 [1]
第2行 [1,1] =[0,1]+[1,0]
第3行 [1,2,1] =[0,1,1]+[1,1,0]
….
第n行的数据等于上一行n-1行的数据加一个0的错位相加
n-1行:[0]+[1,….1]+[1,…,1]+[0]

def triangles():
s=[1]
while True:
yield s
s=[sum(i) for i in zip([0]+s,s+[0])]
n=0
for t in triangles():
print(t)
n+=1
if n==10:
break
这里应用了zip函数,我们看看zip函数的使用

s=[1,2,3]
for i in zip(s,s):
… print(i)

(1, 1)
(2, 2)
(3, 3)

原创粉丝点击