python:用递归方法编写二分法查找函数 程序报错

在python上用递归方法编写二分法查找函数
程序如下:

def find_loc(x,arr):
    end = len(arr)-1
    mid = end//2
    if len(arr) < 1:
            x_loc = 0
            print("None")
    elif len(arr) > 1:
        if x < arr[mid]:
            b = arr[:mid]
            x_loc = find_loc(x,b)
        elif x > arr[mid]:
            b = arr[mid:]
            x_loc = mid + find_loc(x,b)
        elif x == arr[mid]:
            x_loc = mid+1
    return x_loc

a=[1,2,3,4,5,6,7]
print(find_loc(1,a))

报错如下:

Traceback (most recent call last):

File "binary_search2.py", line 19, in
print(find_loc(1,a))
File "binary_search2.py", line 10, in find_loc
x_loc = find_loc(x,b)
File "binary_search2.py", line 10, in find_loc
x_loc = find_loc(x,b)
File "binary_search2.py", line 16, in find_loc
return x_loc
UnboundLocalError: local variable 'x_loc' referenced before assignment

求助:为什么会出现local variable 'x_loc' referenced before assignment

1个回答

在def find_loc(x,arr):
下面加上
x_loc = 0

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问