首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >bisection_search产生意外的无结果

bisection_search产生意外的无结果
EN

Stack Overflow用户
提问于 2018-08-21 01:03:10
回答 1查看 27关注 0票数 1

我正在按照指令编写一个bisection_search:

代码语言:javascript
复制
import random
arr = list(range(11))
random.shuffle(arr)
m = 9
#list is a stack in python
def bisection_search(m, arr):
    top_index = len(arr) - 1 # rather than top_index = -1 
    bottom_index = 0
    while  bottom_index <= top_index:
        mid_index = (top_index + bottom_index) // 2
        pivot = arr[mid_index]
        if m == pivot:
            return mid_index
        if m > pivot:
            bottom_index = mid_index + 1
        else:
            top_index = mid_index - 1
    return None

target_index = bisection_search(m, arr)
print(target_index)
## -- End pasted text --
None

我使用了ipython的%paste,它没有返回,

另一种尝试:

代码语言:javascript
复制
In [3]: arr
Out[3]: [4, 10, 7, 3, 0, 1, 9, 6, 2, 5, 8]

In [4]: m
Out[4]: 9

In [5]: bisection_search(m, arr)

In [6]: x = bisection_search(m, arr)

In [7]: x

In [8]: def bisection_search(m, arr):

我仔细检查了密码,确认里面没有窃听器。

怎么可能没有结果呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-08-21 01:23:33

  1. 正如其他人所提到的,二分/二进位搜索只适用于排序序列。您将得到无,因为它将根据条件检查随机跳来跳去,并且可能不会最终命中相等的检查条件,并因此返回None。
  2. 除非您有具体的理由来实现您自己的均分,否则请使用已经可用的https://docs.python.org/2/library/bisect.html
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51940279

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档