学习了廖雪峰的官方网站的python一些基础,里面有个题目,就是让写出杨辉三角的实现,然后我就花了时间实现了一把。思路也很简单,就是收尾插入0,然后逐层按照杨辉三角的算法去求和实现杨辉三角。
附属代码:
1 # -*- coding: utf-8 -*- 2 3 # 期待输出: 4 # [1] 5 # [1, 1] 6 # [1, 2, 1] 7 # [1, 3, 3, 1] 8 # [1, 4, 6, 4, 1] 9 # [1, 5, 10, 10, 5, 1] 10 # [1, 6, 15, 20, 15, 6, 1] 11 # [1, 7, 21, 35, 35, 21, 7, 1] 12 # [1, 8, 28, 56, 70, 56, 28, 8, 1] 13 # [1, 9, 36, 84, 126, 126, 84, 36, 9, 1] 14 15 def triangles(): 16 17 L = [1] 18 yield L 19 while True: 20 # print 'L是:',L 21 22 # 在L这个List头尾插入0 23 L.insert(0,0) 24 L.insert(len(L),0) 25 26 n = 0 27 # print 'n:%d--L的长度%d'%(n,len(L)) 28 T = [] 29 while n < len(L)-1: 30 T.append(L[n]+L[n+1]) 31 n = n+1 32 33 L = T 34 yield L 35 36 n = 0 37 for t in triangles(): 38 print(t) 39 n = n + 1 40 if n == 10: 41 break