Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 358
Tlat Avatar asked Oct 08 '19 18:10

Tlat


2 Answers

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)

like image 69
LocoCharles Avatar answered Oct 06 '22 01:10

LocoCharles


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')
like image 31
Mad Physicist Avatar answered Oct 06 '22 00:10

Mad Physicist