杨辉三角
代码:
def fun(n):
a = []
for i in range(n):
a.append([])#[[],[],[],[],[]]
for j in range(n):
a[i].append(0)#此处以n=5为例:[[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]]
#填几占位都行,不然后面无法用索引,我这里填了0
for i in range(n):
a[i][0]=1#第一位改成1
a[i][i]=1#最后一位改成1
for i in range(2,n):
for j in range(1,i):
a[i][j]=a[i-1][j-1]+a[i-1][j]#a[i][j]=它肩上两个数的和
for i in range(n):
for j in range(i + 1):
print(str(a[i][j]),end=' ')#列表转化成字符串
print()
def main():
n=int(input('请输入要显示几行杨辉三角:'))
fun(n)
if __name__ == '__main__':
main()
输出:
请输入要显示几行杨辉三角:5
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1