Outputting height of a pyramid

Question:

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.

Asked By: Tlat

||

Answers:

A pyramid of height N has 1 + 2 + … + N blocks in it. This reduces to N * (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')
Answered By: Mad Physicist

Let’s think by other way:

Each row in the pyramid is the ‘row’ above + 1 and when finishing all rows then the sum of all rows are equal or ‘bigger’ which is the total number of blocks.

So, if you try by this method you have the follow code:

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}")

So, it runs how you want but neglects the "Complete rows" part.

Answered By: de_python

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
Answered By: Pete

If the blocks number is 6, the height is 3. But if the blocks number is 7, the bottom will be placed with 4 blocks. So the height will be only 2. Because 4+3 is 7.

If the blocks number is 20, the height will be only 5. Because the bottom is 6, and 6+5+4+3+2 gives us 20. And the height is only 5.

Here is the code:

blocks = int(input("Please input block numbers: "))

my_dict = {}

for num in range(1, blocks+1):
    my_dict[num] = (1 + num) * num / 2

for index, value in my_dict.items():
    if value == blocks:
        print(f"The height is {index}")
        break

    if value > blocks:
        _sum = 0
        bottom = index
        for num in range(index):
            _sum = _sum + bottom
            bottom -= 1
            if _sum >= blocks:
                print(f"The height is {num+1}")
                break
        break

Hope it helps.

Answered By: Tyrion

A pyramid with height n has 1 + 2 + … + n blocks. That’s also (n^2+n)/2.

Can you solve from here? You can use the function.

Answered By: sirswagger21
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)

Answered By: LocoCharles

Here’s what I came up with because while building the pyramid if the remainder of the blocks are not sufficient you cannot complete the next/final layer/row.

Here’s the code:

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

height = 0

rows = 1

while rows <= blocks:

    height += 1
    blocks -= rows
    if blocks <= rows:
        break
    rows += 1

print("The height of the pyramid: ", height)
Answered By: JonesEmjay
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)
Answered By: Swalker66
blocks = int (input("Enter the number of blocks: ")
height = 0
min_blocks = 0

for blokken in range (1, blocks + 1):
    if ((min_blocks + blokken) <= blocks):
        min_blocks = min_blocks + blokken
        height = height + 1
print ("The height of the pyramid: ", height)
Answered By: Lovanium
sum = 0
block =int(input()) 
for height in range(1,block):
    sum = sum+height
    if(sum == block):
     print("the height of pyramid:",height)
Answered By: harichandan
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)
Answered By: Jaydip Patil

I set the count variable to count the height. When only the blocks variable is greater than or equal to 1, it runs the while loop.

In the while loop, there are conditional clauses to be separated from when blocks == 1 and others. In the condition of the others, count plus 1 for each iteration and set total variable as the normalized blocks to compare with the user-inputted blocks. When total is equal to blocks, height is count and escape while loop. Else if total is greater than blocks, height is equal to count - 1 and escape while loop.

blocks = int(input("Enter the number of blocks: "))
count = 1

while blocks >= 1:
    if blocks == 1:
        height = count
        break
    else:
        count += 1
        total =0
        for i in range(1, count+1):
            total += i
        if total == blocks:
            height = count
            break
        elif total > blocks:
            height = count -1
            break

print("The height of the pyramid:", height)
Answered By: Peter Fan

hello guys this solution using both (for & while) loop

Using for loop

blocks = int(input('Enter number of blocks:'))
j = 0
for i in range(1,blocks):       
    j = j + I
    if j > blocks:
        i = i-1
        break    
    height = I
    print("The height of the pyramid:", height)    

Using while loop

blocks = int(input('Enter number of blocks:'))
j = 0
i = 0
while i < blocks:
    i = i + 1
    j = j + I
    if j > blocks:
        i =i-1
        break    
    height = I
    print("The height of the pyramid:", height)
Answered By: Mohammed Altyeb

This is the best solution that I could derive:

blocks = int(input("Enter the number of blocks: "))                      
                                                                         
height = 0                                                                                                                              
while height < blocks:                                                   
    height += 1                                                          
    blocks -= height
                                                   
print(height)
Answered By: Deven Suji

To begin with the total is 0 so if a user inputs say 6 blocks, definitely blocks are more than total in this case the else part executes.

The else statement keeps counting the height and summing it up to the total until it reaches the total number of blocks. It sums up the height because the row below is always height+1: So what is basically happening is this: 1+2+3+….+n .

And The if block helps us to exit the loop. "blocks <= total" , the less than (<) is because if the blocks are like 2 they are not enough to build a pyramid of height 2 so it should print the height as 1; so total should be less or equal to the blocks.

Hope this helps.

blocks = int (input("Number of blocks: "))
height = 0
total = 0

#loop until there are no more blocks    
while blocks:
   #this is the base condition which tells us when to exit the loop
   if blocks <= total:
      break
   else:
      height += 1
      total += height
print("Height is: ", height)
Answered By: 004_
blocks = int(input("Enter the number of blocks: "))
y = 0
x = 0
for x in range(0 , 99999999999999):
     if  y == blocks:
        height = x
        break
     elif y > blocks:
        height = x - 1
        break
     else:
        y += x  + 1
        height = x - 1
print("The height of the pyramid:", height)
Answered By: freedomultd

Let,
h -> height of the pyramid
n -> number of blocks

h can be calculated using the equation h = (-1 + sqrt(1 + 8n))/2. (Remove the floating value and consider only the integer part)

If you are intrested how the eaquation is derived, here is the explanation.

Here is the equation to calculate the height of a pyramid of n blocks :

h(h+1)/2 = n

Simplify the equation.

h^2 + h = 2n

Transforming it into quadratic equation of the form aX^2 + bX + c = 0, we get :
h^2 + h -2n = 0

Comparing h^2 + h -2n = 0 with aX^2 + bX + c = 0 we get :a = 1, b = 1, c = -2n

Put these value in the quadratic formula X = (-b + sqrt(b^2 – 4ac))/2 (Ignoring -ve solution).
So,
h = (-1 + sqrt(1 + 8n))/2 -> final eqaution to calculate the height of pyramid with n blocks.

Rest is simple programming.

PS: sqrt stands for square root.

Answered By: Shashi Shekhar

First, I created a new variable called "Height" and assigned it with the value 0.

Then I created another variable called "Levels" to track the blocks used on each layer of the pyramid. I also assigned it a value of 0.

Why?:
The "Level" variable is necessary for use in comparing left over blocks to the last layer of the pyramid. Example – If you have 10 blocks left and your last layer was 10, you cannot create another layer because each one is supposed to have 1 block more.

When the variables "Level" and "Block" are the same, the loop is broken.

blocks = int(input("Enter the number of blocks: "))
height = 0
levels = []

while blocks > 0:
    height += 1
    blocks -= height
    levels.append(height)
    if blocks <= levels[-1]:
         break

print("The height of the pyramid:", height)
print(levels)
print(blocks)
Answered By: CassyE

I’ve come with this solution. I think is fairly simple, but does attend to the solution.

We have the height starting at 0 and the blocks_out variable, which is every block that is added to the second, third, fourth… level of the pyramid.

So I made a while loop, which will stop when the number of blocks stay equal to the height meter or below it. It will prevent that the program complete a level without having enough blocks to do it. If it has, then the height will be under block’s quantity and it will be able to complete a full level.

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

height = 0
blocks_out = 1

while height < blocks:    
    blocks = blocks - blocks_out # blocks diminish, beginning with the first top block
    height += 1                  # put first block, first level done
    blocks_out += 1              # adittional block to each level that comes after


print("The height of the pyramid:", height)
Answered By: Gilberto Costa

When you invert your pyramid, you’re simply counting from 0 (height 0) and incrementing by 1. This also corresponds to the maximum blocks for each "inverted" level.
So:

  • inverted height 1: 1 block (maximum)
  • inverted height n: n blocks (maximum)

Using a while loop, this looks like a simple solution:

blocks = int(input("Enter the number of blocks: "))
height = 0
while blocks > 0:             # as long as there are blocks
    if blocks - 1 >= height:  # remaining blocks vs number needed to fill the height level
        height += 1           # height is same as number of blocks in "inverted level"
    blocks = blocks - height  # remain after level completion
print("The height of the pyramid:", height)
Answered By: Martin N

Understand the logic:
At the top, we have 1 block so the height is 1.
The second level will have 2 blocks.
Thrid level will have 3 blocks… and so on.

1st level- 1 Block
2nd Level- 2 Blocks
3rd Level- 3 Blocks

Answered By: Suraj Shrivastava
blocks = int(input("Enter the number of blocks: "))
layer_block = 0
i = 1
height = 0
while True:
    layer_block = layer_block + i
    i = i + 1
    if layer_block > blocks:
        break
    height = height + 1
print("The height of the pyramid:", height)
Answered By: chengxuyuan9527

For this coding exercise, I simply had a top to bottom approach by increasing the each blocks layer by layer.

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

height = 0

while blocks > height :

  height +=1
  blocks = blocks - height

print("The height of the pyramid:", height)

Answered By: Varun
n = int(input("Enter the number of blocks: "))
height=0
i=0
while n>i:
      i+=1
      n=n+1
      height+=1 
print("The height of the pyramid:", height)

thank you
Answered By: wryon

Give this a try: Kept it as simple as possible.

height = 1
totalBlocks = 0

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

while totalBlocks + height <= blocks:
    totalBlocks += height
    height += 1

print("The height of the pyramid is:", height - 1)
Answered By: JotaPe16

VERY new to IT… python is the first language I’m learning, but I’m pretty sure this works:

height = 0
width = 1
next_width = 1
        
while blocks >= next_width:
    blocks - width
    height += 1
    blocks -= next_width
    next_width += 1
           
print("The height of the pyramid:", height)
Answered By: Bryant Logan

logic is putting an object in increasing order where top-level contains 1 and top-1 contains 2 and so on..Here passing array length and count=1 logic behind recursively call the same method until n>=count. For 1st call n=4 and count=1,for 2nd call n=3 and count=2 , for 3rd call n=1 and count=3 here condition fail and we return count-1.

/*Given n objects, with each object has width wi. We need to arrange them in a pyramidal way such that : 
    Total width of ith is less than (i + 1)th.
    Total number of objects in the ith is less than (i + 1)th.*/
public class Max_Height_Pyramid 
{
    static int pyramidHeight(int n,int count)
    {
        while(n>=count)
        {
            n=n-count;
            count++;
            pyramidHeight(n,count);
        }
        return count-1;
    }
    public static void main(String args[])
    {
        int[] boxes= {10,20,30,50,60,70};
        int n=boxes.length;
        int count=1;
        int result=pyramidHeight(n,count);
        System.out.println(result);
    }

}

Answered By: NIlesh Pingale
blocks = int(input("Enter the number of blocks: "))

height = 0

last_row_num = 0

LRN = last_row_num

while blocks > LRN:
    LRN = LRN + 1
    height = height + 1
    blocks = blocks - LRN
    if blocks <= LRN:
        break

print("The height of the pyramid:", height)

This is what i used and it worked great try yourself 🙂
and it was fairly easy to understand.

Answered By: Thegreatcodinni
blocks=int(input("Enter the number of blocks:"))
b=blocks
n=1
while n*(n+1)//2 <=b :
    h=n
    n=n+1
print("The height of the pyramid is", h)
Answered By: Nimmy Joseph
height = 0
used_blocks = 0

while blocks > 0:
    used_blocks += 1
    if blocks >= used_blocks:
        blocks -=  used_blocks
    else:
        break
    height += 1
Answered By: Z Khoo
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.