在Python中,杨辉三角总是拿出来当算法题考,那什么是杨辉三角呢?查看定义
先来观察下面的杨辉三角图例:

通过观察会发现,杨辉三角的每行的第一个与最后一个数都是1,且从第3行开始非1数字是它左上方和右上方的数的和 !
那么知道了规律就可以开始写代码了
1def triangles(row): 2 count = 0 3 while count < row: 4 arr = [] 5 for i in range(count+1): 6 if i > 0 and i < count: 7 arr.append(lastList[i-1] + lastList[i]) 8 else: 9 arr.append(1) 10 lastList = arr 11 yield arr 12 count += 1 13 14 15for t in triangles(10): 16 print(t)
上面代码写完了,看着这么多代码,那么是不是可以把代码简化一些呢?
然后就有了下面代码
1def triangles(row): 2 count = 0 3 while count < row: 4 arr = [arr[i-1] + arr[i] if i > 0 and i < count else 1 for i in range(count+1)] 5 yield arr 6 count += 1 7 8 9for t in triangles(10): 10 print(t)
这样代码就简洁很多了