Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
64 views
in Technique[技术] by (71.8m points)

python - Returns wrong output for the pyramid problem

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?

Problem

question from:https://stackoverflow.com/questions/65873320/returns-wrong-output-for-the-pyramid-problem

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is an implementation with just a while loop

number=1000
count=0
while number >= count:
    count +=1
    number -= count

print(count)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...