我不确定您要打印的确切内容,但我知道该功能可能存在一些不当行为。尝试这样的事情:
# binary search for list with desending values
def binary_search(li, targetValue):
low, high = 0, len(li) - 1 # min & max index
while low <= high: # loop til high & low switch
mid = (high + low) / 2 # midpoint (rounds down)
if li[mid] > targetValue: low = mid + 1 # confine to upper half
elif li[mid] < targetValue: high = mid - 1 # confine to lower half
elif li[mid] == targetValue: return mid # found it!
return None # nothing to return (low/high switched, so it wasn't found)
targetValue
如果在 中li
,这将返回匹配的索引,None
否则。像这样使用:
li = [10000, 1000, 100, 10, 1]
if binary_search(li, 500) is None: print '500 not found!'
else: print '500 found!'
i = binary_search(li, 10)
if i is None: print '10 not found!'
else: print 'Found 10 at index ' + str(i) + '!'
那将输出:
500 not found!
Found 10 at index 3!
要加入li
,只需切换<
和>
:
def binary_search(li, targetValue):
low, high = 0, len(li) - 1
while low <= high:
mid = (high + low) / 2
if li[mid] < targetValue: low = mid + 1
elif li[mid] > targetValue: high = mid - 1
elif li[mid] == targetValue: return mid
return None