1 写作动机
答案太过于敷衍了事,完全体现不出杨辉三角的性质,自己重新编码了一下。
2 答案参考代码
#!/usr/bin/python3.8
# -*- coding: utf-8 -*-
# @Time : 2021/6/23 11:24
# @Author : Yujie_Xue
# @Email : xyj19970628@163.com
# @File : 7.6 yanghui_angle_answer.py
# @Software: PyCharm
# 答案太垃圾!!根本没有体现出杨辉三角的性质
def main():
num = int(input('Number of rows: '))
yh = [[]] * num
for row in range(len(yh)):
yh[row] = [None] * (row + 1)
for col in range(len(yh[row])):
if col == 0 or col == row:
yh[row][col] = 1
else:
yh[row][col] = yh[row - 1][col] + yh[row - 1][col - 1]
print(yh[row][col], end='\t')
print()
if __name__ == '__main__':
main()
输出:
3 我的编码
#!/usr/bin/python3.8
# -*- coding: utf-8 -*-
# @Time : 2021/6/22 23:45
# @Author : Yujie_Xue
# @Email : xyj19970628@163.com
# @File : 7.6 yanghui_angle.py
# @Software: PyCharm
# 打印杨辉三角
import numpy as np
def print_angle(n):
# 先初始化
x = np.zeros((n, n))
for i in range(n):
x[i][0] = x[i][i] = 1
# 迭代修改值
max = 0
for i in range(2, n):
for j in range(1, i):
x[i][j] = x[i-1][j-1] + x[i-1][j]
if max < len(str(x[i][j])): max = len(str(x[i][j]))
# 格式输出
for i in range(n):
s = ''
white = ' ' * max
for j in range(i+1):
s += str(int(x[i][j]))
if j != i: s = s + white
if i == 1 and j == 0: s += ' '
print(s.center(n * 2 * max + 2*n))
# 要形成一个恰到好处三角形重点在于此处,要考虑最长的数字长度和数字与数字之间的缝隙大小,最后还要使用字符串居中输出
if __name__ == '__main__':
n = int(input('输入你要的杨辉三角层数:'))
print_angle(n)
输出: