杨辉三角
One:
- triangle = [[1], [1, 1]]
- num = 7
- for n in range(2, num):
- pre = triangle[n - 1]
- cur = [1]
- for j in range(0, n - 1):
- cur.append(pre[j] + pre[j + 1])
- cur.append(1)
- triangle.append(cur)
- for i in triangle:
- print(‘ ‘ * (6 - int(triangle.index(i))), i)
Two:
- triangle = [
- [1],
- [1, 1]
- ] # 初始化一个有0,1两个索引的嵌套列表
- line = 11 # 打印几行杨辉三角
- for index in range(2, line): # 从主列表第2个索引开始
- previous = triangle[index - 1] # 第n行有n个索引,比如第三行,从0,1,2 共三个,最后一个索引是行号减1
- current = [1] # 放一个只有头部 1的新列表
- for index2 in range(0, index - 1):
- current.append(previous[index2] + previous[index2 + 1]) # 迭代把0和1相加结果追加到列表,1和2,2和3,3和4,边界是line,行号就是有line个索引
- current.append(1) # 追加尾部的1
- triangle.append(current) # 把新的行(新的列表)追加到主列表
- for lst in triangle:
- print(‘ ‘ * (line - int(triangle.index(lst))), lst)
Three:
- triangle = []
- line = 11
- for index in range(0, line):
- if index == 0:
- triangle.append([1])
- else:
- previous = triangle[index-1]
- current = [1]
- for index2 in range(0,index-1):
- current.append(previous[index2]+previous[index2+1])
- current.append(1)
- triangle.append(current)
- for lst in triangle:
- print(‘ ‘*(line-int(triangle.index(lst))),lst)
Four:
- n = 7
- oldline = []
- newline =[1]
- length = 0
- print(newline)
- for i in range(1, n):
- oldline = newline.copy()
- oldline.append(0)
- print(oldline)
- newline.clear()
- offset = 0
- while offset <= i:
- newline.append(oldline[offset-1] + oldline[offset])
- offset += 1
- print(newline)
five:
- triangle = []
- n = 10
- count = 0
- for line in range(1, n+1):
- current = [1] * line
- for j in range(1, line):
- count += 1
- if j == 1:
- continue
- else:
- current[j-1] = triangle[-1][j - 2] + triangle[-1][j - 1]
- triangle.append(current)
- print(triangle)
- for j in triangle:
- print(j)
- print(count)
Python练习(九) 杨辉三角
来源: http://www.bubuko.com/infodetail-2343750.html