python实现杨辉三角(使用生成器)

此文转载自:https://blog.csdn.net/duhm163/article/details/48161719

记录一下在初次使用生成器是遇到的问题,具体代码如下:

def triangel(n):
	L = [1]
	while True:
		yield L
		L = [L[x] + L[x + 1] for x in range(len(L) - 1)] #计算中间数字,注意当x为空时,L = []
		print('L = ', L)
		L.insert(0, 1)    #在list首位添加1
		L.append(1)       #在list末位添加1
		if len(L) > n:
			break

if __name__ == "__main__":
	x = triangel(3)
	for n in x:
		print(n)

猜你喜欢

转载自blog.csdn.net/lsy_07/article/details/80742956