weixin_44303190
Tian HaiBao
采纳率0%
2018-12-27 18:23 阅读 785

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条回答 默认 最新

相关推荐