Reputation: 19
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.
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).
blocks = int(input("Enter the number of blocks: "))
height=0
count=1
while(blocks>1):
for i in range(0,count):
blocks -= 1
count +=1
height += 1
print("The height of the pyramid:", height)
It works for 6, but for 1000, it should return 44 but instead I get 45! What's wrong with my code?
Upvotes: 0
Views: 612
Reputation: 1
I coded this myself and found out that many variables are not required. Also I have added some comments for you :)
blocks = int(input("Enter the number of blocks: "))
# Suppose user enters 3 blocks
layer = 0
while(layer<blocks): #0<3; 1<2; 1<0->is false, so goes to else
layer+=1 #0+1=1; 1+1=2;
blocks = blocks - layer #3 = 3-1 = 2; 2-2 = 0
print("Layer added: ", layer)
else:
print("Work stopped! As the blocks are finished for next layer :)")
height = layer #stores last occurrence of layer added, as each layer is height
print("The height of the pyramid:", height)
Now, if you read the comments in my program carefully, you will get the entirety of what's required to be done. Feel free to ask back.
Upvotes: 0
Reputation: 9481
Here is an implementation with just a while loop
number=1000
count=0
while number >= count:
count +=1
number -= count
print(count)
Upvotes: 0
Reputation: 955
You need to add to the count before the for loop and add an ='s.
blocks = int(input("Enter the number of blocks: "))
height=0
count=1
while(blocks>=1):
count +=1
height += 1
for i in range(0,count):
blocks -= 1
print("The height of the pyramid:", height)
Upvotes: 2