杨辉三角python实现

1、根据二项式定理生成杨辉三角

#阶乘算法:

def factorial(n):

    if n == 1 or n == 0:

        return 1

    else:

        return factorial(n-1)*n

#根据二项式定理生成:

def triangle(max):

    L = [1]

    yield L

    L = []

    for i in range(1, max):

        for j in range(0, i + 1):

            L.append(int(factorial(i)/(factorial(i-j)*factorial(j))))

        yield L

        L = []

    return ‘done’

例子:

for t in triangle(10):
print(t)

输出:

[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/streetballerym/article/details/48976637
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞