【问题标题】:How do i fix the 'element not found' in binary search?如何修复二进制搜索中的“找不到元素”?
【发布时间】:2019-08-07 08:35:03
【问题描述】:

我一直在尝试实现此代码,其工作是使用二进制搜索查找特定元素。现在,如果元素存在于列表中,则代码可以正常工作,但如果搜索元素不存在,则无法显示预期的块目前。我假设该列表按升序排序。对此的帮助将不胜感激

我尝试在 while: 中添加 else 部分,但没有帮助。它无法显示未找到元素的错误

def binarysearch(l,item):
    low=0
    u=len(l)-1
    while low<=u:
        mid=int((low+u)/2)
        if item==l[mid]:
            return mid
        elif item<l[mid]:
            high=mid-1
        else:
            low=mid+1
l=eval(input("Enter the list of elements"))
item=int(input("Enter search item:"))
index=binarysearch(l,item)
if index>=0:
    print(item,"found at index",index)
else:
    print("Element not found") #i am unable to reach this part 

如果输入是: 输入元素列表[8,12,19,23] 输入搜索项:10

我希望结果是“找不到元素”。但是在这种情况下程序什么也不做

【问题讨论】:

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


    【解决方案1】:

    我会给你一个提示,稍后我会更好地测试这段代码并尝试解释它发生的原因。 提示是使用in 检查项目是否存在于列表中。 In 比使用循环更具性能。 示例工作:

    def binarysearch(elem, item):
        if item in elem:
            return elem.index(item)
        else:
            return -1 # because your if verifying if the return is equal or greater than 0.
    

    更新 1 当我尝试运行您的代码时,我进入了一个无限循环,这是因为mid=int((low+u)/2) 表达式而发生的 - 我不明白您为什么这样做。如果我们运行这段代码会发生这样的情况:

    1. 列出 [8,12,19,23] 和第 10 项
    2. u=len(l)-1 u = 3 因为 4 - 1
    3. 进入while,因为条件为真
    4. mid=int((low+u)/2) 这里 mid 将是 (0+3)/2 因为你强制它是 int 结果将是 1
    5. if item==l[mid]: 10 == 12 -- l[mid] - l[1] - False
    6. elif item&lt;l[mid]: 10
    7. high=mid-1 高为 1 - 1 = 0
    8. 您从数字 3 开始进入下一个迭代,这就是您进入无限循环的原因 要遍历列表中的所有位置,您可以使用从 0 开始的 low,如果 item 不是 == 该位置的值,则增加。所以你可以使用while,但是这样:
    def binarysearch(l,item):
        low=0
        u=len(l)-1
        while low<=u:
            if item==l[low]:
                return low
            else:
                low+=1
    
        return -1
    l=eval(input("Enter the list of elements"))
    item=int(input("Enter search item:"))
    index=binarysearch(l,item)
    if index>=0:
        print(item,"found at index",index)
    else:
        print("Element not found")
    
    

    要调试您的代码,您可以使用 [1]:https://docs.python.org/3/library/pdb.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-10-02
      • 1970-01-01
      • 1970-01-01
      • 2019-09-15
      • 2018-05-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多