zoukankan      html  css  js  c++  java
  • Python杨辉三角算法

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    def triangles():
          n = 1
          aboveList = []
          while True:
              if n == 1:
                  aboveList = [1]
                  n = n + 1
                  yield [1]
              if n == 2:
                  aboveList = [1,1]
                  n = n + 1
                  yield [1,1]
              newList = []
              for x in getMiddleList(aboveList):
                  newList.append(x)
              newList.insert(0,1)
              newList.append(1)
              aboveList = newList
              n = n + 1
              yield newList
          return 'done'
    
    def getMiddleList(aboveList):
        newList = []
        leftNodeVal=0 
        n=1
        for x in aboveList:
            if n == 1:
                leftNodeVal = x
            else:
                newList.append(x+leftNodeVal)
                leftNodeVal = x
            n += 1
        return newList
    
    n=0
    for t in triangles():
        print(t)
        n = n + 1
        if n == 10:
            break

    输出结果:

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

    精简后的算法:

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    def triangles():
        l = [1,0]
        while True:
            yield l[0:-1]
            l[1:-1] = [l[i-1]+l[i] for i in range(1, len(l))]
    
    n=0
    for t in triangles():
        print(t)
        n = n + 1
        if n == 10:
            break        
  • 相关阅读:
    Unity调试模式设置辅助线是否可见
    Gizmos绘制塔防游戏网格
    JS offsetparent 问题
    JS 图像延迟加载
    JS image对象
    JS 瀑布流
    JS 对象
    JS node
    Vue+element 实现表格的增加行、根据索引删除行的功能
    Java的集合框架
  • 原文地址:https://www.cnblogs.com/frankyou/p/5730257.html
Copyright © 2011-2022 走看看