对于102层楼和7个蛋的破蛋问题,Python中是否有非递归解决方案



我是一个新手程序员,学习Python使用这本书:"使用Python的计算和编程导论";约翰·V·古拉格。我正在尝试第3章中的手指练习:"帝国大厦有102层楼高。一个男人想知道他能在不打碎鸡蛋的情况下扔鸡蛋的最高楼层。如果它坏了,他会从地板上下来再试一次。他会这样做,直到鸡蛋不碎为止。最坏的情况下,这种方法需要102个鸡蛋。实现最坏情况下使用7个鸡蛋的方法";。我是这样实现的。我不知道这是否是最有效的非递归方法///

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)

///

我在读同一本书,发现了这个问题。我想你不需要数这个问题还剩多少鸡蛋。因为在这种情况下,通过使用平分搜索,答案将在不到7次尝试的情况下找到。

这就是我解决问题的方法:

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)

最新更新