用Python输出金字塔的高度

2024-04-28 10:16:47 发布

您现在位置:Python中文网/ 问答频道 /正文

告诉我,这个金字塔有多少行是完整的,我要做的就是把它编码成多行。在

例如,如果我输入6个方块…我希望它告诉我金字塔的高度是3。(底部3块,上面2块,上面1块)。在

在我的头脑中,我觉得这将类似于一个斐波纳契金字塔,所以我的基础上我的代码。在

blocks = int(input("Enter number of blocks: "))

for i in range(blocks + 1):
    for j in range(blocks + 1):
    height = j / 2
if height % 2 == 0:
    height = height / 2

print(f"The height of the pyramid: {height}")

这就是我目前所拥有的。。。如果我做数字6或20,这是可行的,但很明显,如果我做1000,它不会给我我想要的结果。我觉得我离我的代码太远了。在


Tags: of代码in编码forinput高度range
3条回答

注意,有n行的块的和是n*(n+1)/2。对于匹配的块编号floor(sqrt(2*x))将给出正确的结果,对于其他数字,它可以是1到大,因此将结果放入n*(n+1)/2,如果太大,则减少1。在

Height=floor(sqrt(2*x))
if(x<height*(height+1)/2) height=height-1

换个角度想想:

金字塔中的每一行都是大约+1的“行”,并且在该行中完成的行数比所有行的总和相等或“更大”,即总块数。在

因此,如果您尝试使用此方法,您将得到以下代码:

blocks = int(input("Enter number of blocks: "))
height = 0
by_row = 0
total = 0
for i in range(blocks):
    if blocks <= total:
        break
    height += 1
    by_row += 1
    total += by_row

print(f"The height of the pyramid:{height}")

所以,这是你想要的跑步方式。在

高度为N的金字塔中有1 + 2 + ... + N块。这减少到N * (N + 1) / 2。所以您需要找到(N^2 + N) / 2形式的最大整数,它小于或等于您选择的数字blocks。二次函数相当简单:N^2 + N - 2 * blocks = 0,根在N = floor((-1 +/- sqrt(1 + 8 * blocks)) / 2)。由于blocks是一个正整数,负根永远不会应用于您的情况。您可以使用int表示floor,使用{}表示{},得到:

blocks = int(input("Enter number of blocks: "))
print(f'You can build a pyramid {int(0.5 * ((8 * blocks + 1)**0.5 - 1))} blocks high')

相关问题 更多 >