Python学习笔记(4) -- (关键词:杨辉三角、生成器)

来源:互联网 发布:python canny边缘检测 编辑:程序博客网 时间:2024/06/01 13:37

链接:

http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0014317799226173f45ce40636141b6abc8424e12b5fb27000


练习

杨辉三角定义如下:

          1        1   1      1   2   1    1   3   3   1  1   4   6   4   11   5   10  10  5   1

把每一行看做一个list,试写一个generator,不断输出下一行的list:

# -*- coding: utf-8 -*-def triangles():
# 期待输出:# [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]n = 0for t in triangles():    print(t)    n = n + 1    if n == 10:        break

方法1:

#易于理解的方法,注:append并不是不是数组加法运算哦。def triangles():    #初始化输出数组    myList = [1]     #定义临时数组    tempList = []     while True:        #输出第一行数组        yield myList         #在输出数组后添加一项。        myList.append(0)         #遍历添加新数组内容        for x in range(len(myList)):         #每次append之后,myList数组都会有变化        tempList.append(myList[x-1] + myList[x])         #将临时数组中的内容赋值给输出数据        myList = tempList         #临时数组清空,为下一次存储做准备。        tempList =[] n = 0for t in triangles():    print(t)    n = n + 1    if n == 10:        break

方法2

def triangles():    L = [1]    while True:     #进入持续循环        yield L   #输出数组        L.append(0) #为数组添加最后一位        L = [L[i - 1] + L[i] for i in range(len(L))] #为什么这里不需要临时数组?因为在[]中的内容未完成之后,L并不会产生变化。n = 0for t in triangles():    print(t)    n = n + 1    if n == 10:        break

原创粉丝点击