我想为python创建一个三角形,它需要看起来像:
8 7 6 5 4 3 2 1
8 n
7 n n
6 n n n
5 n n n n
4 n n n n n
3 n n n n n n
2 n n n n n n n
1 n n n n n n n n
我的代码是:
import math
def combination(n,m):
return int((math.factorial(n))/((math.factorial(m))*math.factorial(n-m)))
def main():
print("|",end='')
for n in range(8,0,-1):
print(" ",n,end='')
print()
print("--------------------------------------")
for m in range(8,0,-1):
print(m,"|",end='')
for n in range(8,0,-1):
if(n>=m):
print(format(combination(n,m),"4d"),end='')
else:
print()
main()
请帮忙。
答案 0 :(得分:0)
好像你打印的是不必要的空白行。您需要在break
语句中添加else
语句。还要在第一个print语句中添加几个空格以对齐表,并将格式语句添加到第二个print语句,以便在m
的位数增加时获得一致的输出。
import math
def combination(n,m):
return int((math.factorial(n))/((math.factorial(m))*math.factorial(n-m)))
def main():
print(" |",end='')
for n in range(8,0,-1):
print(format(n, "4d"), end='')
print()
print("--------------------------------------")
for m in range(8,0,-1):
print(m,"|",end='')
for n in range(8,0,-1):
if(n>=m):
print(format(combination(n,m),"4d"),end='')
else:
print()
break
print()
main()
# | 8 7 6 5 4 3 2 1
# --------------------------------------
# 8 | 1
# 7 | 8 1
# 6 | 28 7 1
# 5 | 56 21 6 1
# 4 | 70 35 15 5 1
# 3 | 56 35 20 10 4 1
# 2 | 28 21 15 10 6 3 1
# 1 | 8 7 6 5 4 3 2 1