• python 杨辉三角


    是我写的普通不用生成器版本:

    l=[]
    for i in range(10):
    l.append([])
    for j in range(i+1):
    l[i].append(0) #用0占位置,我之前没有占位置时候,初始化为l=[[],[]]会显示index out of range.不知道为何,我是初学者。
    if j==0 or j==i:
    l[i][j]=1 #两端为1
    else:
    l[i][j]=l[i-1][j-1]+l[i-1][j] #中间数为上两数之和
    print "%4d"%l[i][j], #输出
    print

    ————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
    我后来百度了一下,用生成器的也有几个版本,前面格式都一样。获取下一列的方式不一样。版本一:
    def triangles():
        L = [1]
        while True:
            yield L
            L.append(0)
            L = [L[i - 1] + L[i] for i in range(len(L))] #用前一个list 生成后一个list每一个元素。第一个元素等于  l[-1] +l[1] (0+-1)

    版本二:

    def triangles():  
      L = [
    1] 
      while True:
        yield L
        L=[sum(i) for i in zip([0]+L,L+[0])]
    #创造两个list 错位+
     
    
    
  • 相关阅读:
    python list添加元素的几种方法
    Python ---- list和dict遍历
    python 之 collections
    python list 中元素的统计与排序
    pandas dataframe 读取 xlsx 文件
    Python 缓存机制与 functools.lru_cache(zz)
    pip 使用
    python 中的异常处理
    python 时间日期处理
    python read txt file
  • 原文地址:https://www.cnblogs.com/hello1123/p/7347307.html
Copyright © 2020-2023  润新知