使用递归的方法打印杨辉三角

def young_triange(num_rows):
	if num_rows == 1:
		return [[1]]
	elif num_rows ==2:
		return [[1],[1,1]]
	else:
		new_col = [1]
		for i in range(1,num_rows-1):
			new_ele = young_triange(num_rows-1)[num_rows-2][i-1]+young_triange(num_rows-1)[num_rows-2][i]
			new_col.append(new_ele)
		new_col.append(1)
		res = young_triange(num_rows-1)
		res.append(new_col)
		return res

tri = young_triange(8)
for i in tri:
	print(i)

结果:

[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
[1, 6, 15, 20, 15, 6, 1]
[1, 7, 21, 35, 35, 21, 7, 1]
[Finished in 1.0s]

你可能感兴趣的:(#,python习题)