python中的数字金字塔 [英] pyramid of numbers in python
本文介绍了python中的数字金字塔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
编写一个程序,提示用户输入一个 1 到 15 之间的整数并显示一个金字塔,如以下示例运行所示:
Write a program that prompts the user to enter an integer from 1 to 15 and displays a pyramid, as shown in the following sample run:
1
2 1 2
3 2 1 2 3
4 3 2 1 2 3 4
5 4 3 2 1 2 3 4 5
6 5 4 3 2 1 2 3 4 5 6
7 6 5 4 3 2 1 2 3 4 5 6 7
我有以下几点:
num = eval(raw_input("Enter an integer from 1 to 15: "))
if num < 16:
for i in range(1, num + 1):
# Print leading space
for j in range(num - i, 0, -1):
print(" "),
# Print numbers
for j in range(i, 0, -1):
print(j),
for j in range(2, i + 1):
print(j),
print("")
else:
print("The number you have entered is greater than 15.")
这会导致大于或等于 10 的数字未对齐.
This yields a misalignment for numbers greater than or equal to 10.
我试过 print(format(j, "4d")) 并且所有的数字都没有对齐.
I have tried print(format(j, "4d")) and all the numbers become misaligned.
有什么建议吗?谢谢.
推荐答案
使用前导空格作为数字 ("01" - "09", "10", ...)
Use a leading space for a number ("01" - "09", "10", ...)
num = eval(raw_input("Enter an integer from 1 to 15: "))
def as_str(i):
s = ""
if i <10: s = " "
return s + str(i)
#num = 15
allrows = ""
for j in range(1,num+2):
#leading spaces
row = " "*3*(num-j+1)
#backward
for i in range(j-1,1,-1):
s = as_str(i)
row+=s + " "
#forward
for i in range(1,j):
s = as_str(i)
row+=s + " "
row +="\n"
allrows +=row
print allrows
输出
1
2 1 2
3 2 1 2 3
4 3 2 1 2 3 4
5 4 3 2 1 2 3 4 5
6 5 4 3 2 1 2 3 4 5 6
7 6 5 4 3 2 1 2 3 4 5 6 7
8 7 6 5 4 3 2 1 2 3 4 5 6 7 8
9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9
10 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 10
11 10 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 10 11
12 11 10 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 10 11 12
13 12 11 10 9 8 7 6 5 4 3 2 1 2 3 4 5 6 7 8 9 10 11 12 13
这篇关于python中的数字金字塔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文