【发布时间】:2018-04-30 00:26:24
【问题描述】:
我想为我的函数输出True 的第一个值。我目前的搜索效果很好,但我认为仍然有点低效。谁能建议一个更好的二分搜索?我的代码在下面,经过简化。
guess = 2
limits = [2, 2**35] #The search area
while True:
if myFunction(guess) == False:
limits[0] = max(limits[0], guess) #Limit the search area
guess *= 2
else:
limits[1] = min(limits[1], guess) #Limit the search area
guess = int((limits[0] + limits[1])/2) #The guess is the midpoint of the search area
if myFunction(guess) == True and myFunction(guess-1) == False:
return guess
【问题讨论】:
-
“第一”是什么意思? 范围内的任何 元素满足您的条件?还是最小的?
-
是的,最小的。
-
那么没有理由在范围的中间进行猜测,对吗?如果您希望范围内的第一个值符合您的条件,那么您只需编写
next((x for x in my_range if myFunction(x)), None)。如果这不是您需要的,请告诉我们。 -
@RayToal 我对这个问题的解释(我承认这可能是错误的)是
myFunction对于小于某个数字N的x的值返回 False,并且对于所有值返回 True的x大于或等于N。目标是找到N。因此,可以使用二分查找来查找N,同时调用myFunction不超过35 次。但是next会进行线性搜索,最多可以调用myFunction340 亿次。 -
别担心,我没有花足够的时间阅读它。没关系。我不认为你能比二分搜索做得更好。从中间开始,然后走另一条路。即使知道转折点是更接近开始还是结束,也不会比最简单的二分搜索带来那么多好处,因为 2**35 的搜索空间只需要 35 次探测。
标签: python algorithm binary-search