Venugopal_V_N
Venugopal_V_N

Reputation: 1

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

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)

///

Upvotes: 0

Views: 195

Answers (1)

Zoe
Zoe

Reputation: 1

I am reading the same book and find this question. I think you don't need to count how many egg is left in this question. Becasue in this case, by useing the bisection search, the answer would be find by less than 7 attempts.

This is how I work the question out:

low = 1
high = 120
ans = int((low + high)/2)  # make sure floor is an int
print('drop the egg at floor', ans)
n = input('Did the egg break?')
while (high - low) > 1:
    if n == 'No' or n == 'no':
        low = ans
    else:  # the egg did broke
        high = ans
    ans = int((low + high)/2)
    print('drop the egg form floor', ans)
    n = input('Did the egg break?')
print('egg would break if drop form higher than floor', ans)

Upvotes: 0

Related Questions