102层7个鸡蛋的破蛋问题Python有非递归解法吗?

问题描述 投票:0回答:1

我是一名学习 Python 的新手程序员,正在使用这本书:John V Gurrag 的“Introduction to Computation and Programming Using Python”。 我正在尝试第 3 章中的手指练习: “帝国大厦有 102 层楼高。一个人想知道他可以从哪一层楼扔鸡蛋而不破蛋。如果鸡蛋破了,他会下一层楼再试一次。他会这样做,直到egg didn't break. At worst, this method requires 102 eggs. Implement a method that at worst use 7 eggs". 我是这样实现的。不知道是不是最高效的非递归方法 ///

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)

///

search egg bisection non-recursive
1个回答
0
投票

我正在读同一本书,发现这个问题。我觉得这道题你不用去数还剩下多少个鸡蛋。因为在这种情况下,通过使用二分搜索,不到 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)
© www.soinside.com 2019 - 2024. All rights reserved.