对于我的编程课,我必须创建一个程序来创建一个“金字塔”(在 IDLE 中),如下所示:
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
它会在2**(row)
哪里row = 0
(最初)。它在for
循环中使用。
n
它提出了一个问题,即对于大于 5的值,输出不会像预期的那样出现。
到目前为止,这是我的代码:
def pyramid(n):
rows, num, x, numbers, space_length, i_length = 0, '', 0, {}, 0, 0
for rows in range(n):
x = int(len(num) / 2)
y = str(2**rows) + ' '
num = num[0:x + 1] + y + num[x - 1 :]
numbers[rows + 1] = num
space_length = int(len(numbers[n]) / 2)
for i in numbers:
i_length = int(space_length - (len(numbers[i]) / 2))
numbers[i] = (' ' * i_length) + numbers[i]
print(numbers[i])
def main(): #I have to use the function of main() because my teacher requires it.
n = int(input("Enter an integer greater than 0: "))
if type(n) != int or n <= 0:
raise TypeError("N must be an integer greater than 0.")
pyramid(n)
main()
这是我得到的输出:
>>>
Enter an integer greater than 0: 10
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 1632 16 8 4 2 1
1 2 4 8 1632 64 2 16 8 4 2 1 #The 2 should be 32; space between 16 and 32.
1 2 4 8 1632 64128 64 2 16 8 4 2 1 #Same thing again; spacing messes up.
1 2 4 8 1632 64128256 28 64 2 16 8 4 2 1
1 2 4 8 1632 64128256512 56 28 64 2 16 8 4 2 1
如果有人可以帮我解决这个问题,那就太好了。谢谢!