Is there a non-recursive solution in Python for the egg breaking problem with 102 floors and 7 eggs?

Viewed 14

I am a novice programmer learning Python using the book: "Introduction to Computation and Programming Using Python" by John V Gurrag. I am attempting a finger exercise in Chapter 3: "The Empire State Building is 102 stories high. A man wanted to know the highest floor from which he could drop an egg without the egg breaking. If it broke, he would go down a floor and try again. He would do this until the egg did not break. At worst, this method requires 102 eggs. Implement a method that at worst uses 7 eggs". I implemented it this way. I do not know if it is the most efficient, non-recursive method ///

x = int(input("The highest floor without egg breaking is: "))
eggs_left = 7
low=1
high=102
ans=51
guess_list = [ans]

while eggs_left>0:
    if ans==x:
        print('Highest floor without egg break is',ans)
        print('Sequence of guesses: ',guess_list)
        print('Eggs remaining are: ',eggs_left)
        break
    elif ans<x:
        low=ans
    else:
        high=ans
        eggs_left = eggs_left-1
        print("One egg broken")
        if eggs_left==0:
            print("No more eggs")
            break
        
    if abs(ans-x)>1:
        ans= (high+low)//2
    else:
        ans=x
    guess_list.append(ans)

///

0 Answers
Related