使用默认参数的递归二进制搜索 - Python

时间:2015-02-26 04:22:44

标签: python arrays function python-3.x arguments

我正在尝试在Python中编写一个二进制搜索函数,该函数最初从用户获取两个参数:正在搜索i的值和一个已排序的数组arr。由于它不会总是在数组的同一部分上运行,因此它还需要两个额外的参数,即上限u和下限l;因为我希望初始调用只接受两个参数,我想将0设置为下限的默认值(在递归调用中显然不会这样,其中idx是较低的绑定如果idx < i)和数组的长度作为上限(我不认为我需要加1,因为它总是等于最高指数加1但是如果我错了就纠正我)

我遇到的问题是我无法弄清楚如何将长度作为参数传递。这是我的定义:

def binSearch(arr, i, l=0, u=len(arr)):
    lower = l
    upper = u
    idx = (lower+upper)//2
    print("Lower bound: " + lower + '\n' + "Upper bound: " + upper + '\n' + "Average: " + idx + '\n')

(当然这不是实际的功能,只是初步调试)

这是我运行时收到的错误消息:

Traceback (most recent call last):
  File "/Users/mac/Desktop/programming/python/binarysearch.py", line 1, in <module>
    def binSearch(arr, i, l=0, u=len(arr)):
NameError: name 'arr' is not defined

显然我不能在参数中的参数名称上调用函数,但我想不出另一种可能的方法将'我要使用的数组的长度'转换为Python。有什么帮助吗?

1 个答案:

答案 0 :(得分:3)

将默认设置设为None,如果uNone,请将upper设为len(arr)

def binSearch(arr, i, l=0, u=None):
    lower = l
    if u is not None: # You could do 'if u' if you're sure u is never 0.
        upper = u
    else:
        upper = len(arr)
    idx = (lower+upper)//2
    print("Lower bound: " + lower + '\n' + "Upper bound: " + upper + '\n' + "Average: " + idx 

进行小规模清理:

def binSearch(arr, i, lower=0, upper=None):
    if upper is None:
        upper = len(arr)
    idx = (lower+upper)//2
    print("Lower bound: " + lower + '\n' + "Upper bound: " + upper + '\n' + "Average: " + idx