我的递归二进制搜索程序有什么问题?

时间:2016-11-07 01:04:31

标签: python python-3.x recursion binary-search

我似乎无法弄清楚为什么我的代码会继续返回 N 而不是 R 。在转到return语句之前,我已经测试了字母的内容,正如您在输出图像中看到的那样,它应该是 R 。然而,它继续返回 N ,如图所示,我不知道为什么会这样做......我已经尝试过手动跟踪过程,我仍然最终得到了R.在代码中包含了一些注释,供您查看和理解我的想法。我还在底部包含了输出图片。

输入:['A','B','C','D','E','F','G','H','I','J',' K','L','M','N','O','P','Q','R','S','T','U','V','W' ,'X','Y','Z']

def binSearch(lst, what):
    position = ""
    original_lst = lst[:]
    if (position == what): # Doesn't do anything since no recursive is made when position is equal to R.
        return original_lst.index("%s" %position)
    else:
        midpoint = (len(lst))//2
        position = lst[midpoint]
        print("Looking at", position)
        if position > what:
            lst = lst[:midpoint]
            binSearch(lst, what)
        elif position < what:
            lst = lst[midpoint:]
            binSearch(lst, what)
        elif position == what: # Removable. Just Testing and seeing what position it results as.
            print("Position it ends up in:", position) # when I replace this later, I probably should use a binSearch(). I think?
        else:
            return -1 # this is for if the letter not found.
    return position # Why does it return N... instead of R? This originally was suppose to find the index of the letter on the list. I adjusted it to see what letter the program was searching for instead. It still results in the same problem if I change it to look for the index of letter instead as it looks for **N** instead of **R**
# just to clarify, I was aiming to use return original_lst.index("%s" %position) to find the index of the letter. I just changed it to see what letter its returning instead. 



lst = []
while True:
   val = input()
   if val == "exit":
      break
   lst.append(val)

print(lst)
lst.sort()
print(lst)

what = input("Enter element to search for:")
print(what)
where = binSearch(lst, what)
if where != -1: 
    print("Found at position", where)
else:
    print("Not found")

Picture of Output

编辑:这个程序最初是为了找到这个字母的值。位置被认为是字母,我只会返回。最后指出它。但是为了使它更易读和更容易理解,我在最后更改了return语句。它仍然会产生与 N 而不是 R 相同的结果。

3 个答案:

答案 0 :(得分:1)

第一次调用算法时, N 位于数组的中间。所以这一行

position = lst[midpoint]

position设置为 N 。然后,您 永远不会更改position的值

您应该将两个递归行更改为:

return binSearch(lst, what)

答案 1 :(得分:0)

问题是语法

return position    

这是我得到的

def binSearch(lst, what,low=0, high=None):
  high = len(lst) if high is None else high
  pos = int(low + (high-low)/len(lst))
  if (pos==len(lst)):
    return False
  elif (lst[pos]==what):
    return pos
  elif high==low:
    return False
  elif (lst[pos]<what):
    return binSearch(lst, what, pos + 1, high)
  else:
    assert lst[pos] > what
    return binSearch(lst, what, low, pos)

lst = []
while True:
   val = input()
   if val == "exit":
      break
   lst.append(val)

print(lst)
lst.sort()
print(lst)

what = input("Enter element to search for:")
print(what)
where = binSearch(lst, what)
if where != -1: 
    print("Found at position", where+1) #+1 because the index start from 0
    print (lst[where])
else:
    print("Not found")

希望它有所帮助。

答案 2 :(得分:0)

第一次通过你将会遇到这行代码: position = lst[midpoint] 因此将位置设置为N&#39; 然后你通过搜索递归,但在你执行的每个分支: binSearch(lst, what)。 &#39;位置&#39;这个新的内部binSearch调用中的变量决不会影响外部调用中的位置。如果你想以这种方式编写函数,那么该行应该是这样的:position = binSearch(lst, what)。然后应该正确更新外部调用中的位置。