python实现杨辉三角思路
程序输出需要实现如下效果:
[1]
[1,1]
[1,2,1]
[1,3,3,1]
......
方法:迭代,生成器
def triangles() L = [1] while True: yiled L L =[1] + [L[i] + L[I+1] for i in range(len(L)-1)] + [1] n = 0 for t in triangles(): print(t) n += 1 if n == 10: break
实现逻辑:
1.由于yield为生成器中断输出,所以有了第一个次输出为[1]
2.继续while下面的yield后的循环,此时list长度为1,将其代入L中的len(L),得出[L[i]+L[i+1] for i in range(1-1)]得出为空值,所以yield L输出为[1,1]
3.此时len(L)值为2,代入得出[L[i]+L[i+1] for i in range(2-1)]为[L[i]+L[i+1] for i in range(1)],i能取值为0,代入后为[L[0]+L[1]],而L[0]和L[1]的值均为1(有上面结果可知),所以输出结果为[1,2,1]
4.由第三条可知此时len(L)值为3,代入得出[L[i]+L[i+1] for i in range(2)],i取值为0和1,通过循环输出有两个值,均为3,分别由[L[0]+L[1]],[L[1]+L[2]]
以此类推即可
相关推荐
elizabethxxy 2020-11-06
pythonxuexi 2020-10-30
retacnyue 2020-09-28
pythonxuexi 2020-09-06
Morelia 2020-09-04
zhaobig 2020-08-17
linkequa 2020-08-16
CloudXli 2020-08-14
kikaylee 2020-08-12
LowisLucifer 2020-08-09
xiesheng 2020-08-06
Tristahong 2020-08-05
CatherineC00 2020-08-01
Andrewjdw 2020-07-26
reallyr 2020-07-18
wordmhg 2020-07-16
yawei 2020-07-06
zlfing 2020-07-07