美文网首页
python杨辉三角

python杨辉三角

作者: oh_flying | 来源:发表于2017-05-27 15:28 被阅读29次

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

        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[:]
    

    自己可以试试!

    相关文章

      网友评论

          本文标题:python杨辉三角

          本文链接:https://www.haomeiwen.com/subject/cmeqfxtx.html