python杨辉三角

2017-05-27  本文已影响29人  oh_flying

直接上代码,也是网上找的,自己试了试,很好玩,记录一下:

    def triangles():
        L = [1]
        while True:
            yield L
            L.append(0)
            L = [L[i-1]+L[i] for i in range(len(L))]

定义一个函数,输入打印多少行:

def canshu(k):
     n = 0
    for t in triangles():
             print(t)
             n = n+1
             if n == k:
                    break

调用:

canshu(10)

打印的结果:

[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():
ret = [1]
while True:
    yield ret
    for i in range(1, len(ret)):
        ret[i] = pre[i] + pre[i - 1]
    ret.append(1)
    pre = ret[:]

自己可以试试!

上一篇下一篇

猜你喜欢

热点阅读