python Binary_Search_V2这稍微复杂一些,因为它也会返回项目的索引。还有递归和迭代变体

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python Binary_Search_V2这稍微复杂一些,因为它也会返回项目的索引。还有递归和迭代变体相关的知识,希望对你有一定的参考价值。

def binary_search(a, x):
    mid = (len(a)-1)//2
    if len(a) == 0:
        return -1
    # To catch the edge case where binary_search returns an empty list]
    elif x == a[mid]:
        return mid
    elif len(a) == 1:
        return -1
    # To catch the edge case where binary_search returns one value but it does not match
    elif x < a[mid]:
            return binary_search(a[:mid], x)
    elif x > a[mid]:
        right_value = binary_search(a[mid+1:], x)
        if right_value == -1:
            # the if portion pass -1 up the recursion stack.
            return -1
        else:
            return mid + 1 + right_value
    # write your code here
    
    

def binary_search(a, x):
    left, right = 0, len(a)-1
    while left <= right:
        mid = left+(right-left)//2
        if x == a[mid]:
            return mid
        if x < a[mid]:
            right = mid - 1
        if x > a[mid]:
            left = mid + 1
    return -1
    # write your code here

input = sys.stdin.read()
data = list(map(int, input.split()))
n = data[0]
m = data[n + 1]
a = data[1 : n + 1]
for x in data[n + 2:]:
    print (binary_search(a, x), end = ' ')

以上是关于python Binary_Search_V2这稍微复杂一些,因为它也会返回项目的索引。还有递归和迭代变体的主要内容,如果未能解决你的问题,请参考以下文章

Python学习目录

CentOS python 2.6 升级到 python 2.7

将Python 2转换为Python 3(使用Python 2样式执行)

1-python 2.6 升级到 2.7

CentOS 6.4 升级python 2.6.6 到 python 2.7.9

Python 2.6 升级到 2.7