练习
杨辉三角定义如下:
1
/ \
1 1
/ \ / \
1 2 1
/ \ / \ / \
1 3 3 1
/ \ / \ / \ / \
1 4 6 4 1
/ \ / \ / \ / \ / \
1 5 10 10 5 1
把每一行看做一个list,试写一个generator,不断输出下一行的list:
# -*- coding: utf-8 -*-
def triangles():
arr = [1]
while True:
yield arr
arr = [1] + [arr[i] + arr[i + 1] for i in range(len(arr) - 1)] + [1]
本文介绍了一种使用Python generator实现杨辉三角的方法,通过不断迭代生成每一行的list,展示了数学序列与编程技巧的结合。
237

被折叠的 条评论
为什么被折叠?



