Outputting height of a pyramid in Python
So for this coding exercise I have to input a number of imaginary blocks and it will tell me how many complete rows high the pyramid is.
So for example if I input 6 blocks...I want it to tell me that the height of the pyramid is 3. (3 blocks on the bottom, 2 above that, and 1 above that).
In my head I feel this would work similar to a Fibonacci pyramid so I based my code off of that.
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}")
This is what I have so far... If I do the number 6 or like 20 it works, but obviously if I do something like 1000 it isn't going to give me the result I want. I feel I'm pretty far off with my code.
Solution 1:
blocks = int(input("Enter the number of blocks: "))
height = 0
inlayer = 1
while inlayer <= blocks:
height += 1
blocks -= inlayer
inlayer += 1
print("The height of the pyramid: ", height)
Solution 2:
A pyramid of height N
has 1 + 2 + ... + N
blocks in it. This reduces toN * (N + 1) / 2
. So you need to find the largest integer of the form (N^2 + N) / 2
that is less than or equal to your chosen number blocks
. The quadratic is fairly simple: N^2 + N - 2 * blocks = 0
, with roots at N = floor((-1 +/- sqrt(1 + 8 * blocks)) / 2)
. Since blocks
is a positive integer, the negative root will never apply in your case. You can use int
for floor
and **0.5
for sqrt
to get:
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')
Solution 3:
Note that the sum of block with n rows is n*(n+1)/2. For a matching block number floor(sqrt(2*x)) will give the correct result, with other numbers it can be 1 to large, so put the result into n*(n+1)/2 and if it is too large reduce by 1.
Height=floor(sqrt(2*x))
if(x<height*(height+1)/2) height=height-1
Solution 4:
blocks = int(input("Enter number of blocks: "))
for n in range(blocks):
if n*(n+1)/2 <= blocks:
height = n
print("The height of the pyramid is:",height)