我正在按照说明编写bisection_search:
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
,它返回None,
也尝试过:
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):
我仔细检查了代码并确认没有错误。
如何产生None(无)结果?
答案 0 :(得分:1)