Python实现杨辉三角算法

在Python中,杨辉三角总是拿出来当算法题考,那什么是杨辉三角呢?查看定义

先来观察下面的杨辉三角图例:

通过观察会发现,杨辉三角的每行的第一个与最后一个数都是1,且从第3行开始非1数字是它左上方和右上方的数的和 !

那么知道了规律就可以开始写代码了

def triangles(row):    
    count = 0
    while count < row:
        arr = []
        for i in range(count+1):
            if i > 0 and i < count:
                arr.append(lastList[i-1] + lastList[i])
            else:
                arr.append(1)
        lastList = arr
        yield arr
        count += 1


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

上面代码写完了,看着这么多代码,那么是不是可以把代码简化一些呢?

然后就有了下面代码

def triangles(row):
    count = 0
    while count < row:
        arr = [arr[i-1] + arr[i] if i > 0 and i < count else 1 for i in range(count+1)]
        yield arr
        count += 1


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

这样代码就简洁很多了

猜你喜欢

转载自blog.csdn.net/qczxl520/article/details/108734692