python学习37:生成器方式打印杨辉三角(两种方法)

下面两种方法差不多是一种思路,就是在后面“补0” ,就是在要打印的列表使用yield返回去之后,在后面用append在后面加一个0,好利用杨辉三角的规律,list_new[i] = list_old[i-1] + list_old[i]的规律。

[1]
过渡[1] 0
[1, 1]
过渡[1, 1]0
[1, 2, 1]
过渡[1, 2, 1]0
[1, 3, 3, 1]
过渡[1, 3, 3, 1]0
[1, 4, 6, 4, 1]
过渡[1, 4, 6, 4, 1]0
[1, 5, 10, 10, 5, 1]
过渡[1, 5, 10, 10, 5, 1]0
[1, 6, 15, 20, 15, 6, 1]
过渡[1, 6, 15, 20, 15, 6, 1]0

方法1:

def triangles():
    a = [1]
    while True:
        yield a
        a = [sum(i) for i in zip([0] + a, a + [0])]

n = 0
for t in triangles():
    print(t)
    n = n + 1
    if n == 10:
        break

转载自:https://www.jianshu.com/p/dbc6e7637d3a

方法2:

# -*- coding: utf-8 -*-
 
def triangles():
    N=[1]
    while True:
        yield N        #generator函数与普通函数的差别:在执行过程中,遇到yield就中断,下次又继续执行
        N.append(0)
        N=[N[i-1] + N[i] for i in range(len(N))]  #写法
 
if __name__ == '__main__':
	n=0
	for t in triangles():
		print(t)
		n=n+1
		if n == 10:
			break

转载自:https://blog.csdn.net/sinat_28296297/article/details/77340618

运行结果都是:

==================== RESTART: C:/Users/公有制/Desktop/tri.py ====================
[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]

 

    原文作者:杨辉三角问题
    原文地址: https://blog.csdn.net/weixin_39465823/article/details/88750398
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞