python——杨辉三角
1、定义: 2、基于定义打印 # -*- coding:utf-8 -*- # version:python3.7 n = 6 triangle = [[1],[1,1]] for i in range(2,n): #已经给出前两行,所以求剩余行 cur = [1] #定义每行第一个元素 pre = triangle[i-1] #上一行 for j in range(i-1): #算几次 cur.append(pre[j] + pre[j+1]) cur.append(1) triangle.append(cur) print(triangle) 执行结果: [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1], [1, 5, 10, 10, 5, 1]] # -*- coding:utf-8 -*- # version:python3.7 n = 6 triangle = [] for i in range(n): cur = [1] triangle.append(cur) #先追加进去 if i == 0: continue pre = triangle[i-1] for j in range(i-1): cur.append(pre[j] + pre[j+1]) cur.append(1) print(triangle