【问题标题】:I'm trying to search an item but the program gives incorrect result我正在尝试搜索一个项目,但程序给出的结果不正确
【发布时间】:2019-09-07 14:32:09
【问题描述】:

我在 python 中写了一个线性搜索程序,但它不能正常工作。

我尝试仔细检查程序,但找不到错误。

def LinearSearch(arr, n):

    for i in arr:
        if i == n:
            return i
        else:
            return -1

def main():

    arr1 = [10, 20, 80, 30, 60, 50, 110, 100, 130, 170]
    n1 = 110

    arr2 = [10, 20, 80, 30, 60, 50, 110, 100, 130, 170]
    n2 = 175

    result1 = LinearSearch(arr1, n1)
    if result1 == n1:
        print('Item %d found at index %d' % (n1, result1))
    else:
        print('Item not found')

    result2 = LinearSearch(arr2, n2)
    if result2 == n2:
        print('Item %d found at index %d' % (n2, result2))
    else:
        print('Item not found')

main()

我希望在第一次搜索时输出“元素 x 出现在索引 6”,但它显示“未找到项目”。

【问题讨论】:

    标签: python python-3.x linear-search


    【解决方案1】:

    由于您的LinearSearch 函数在任何情况下始终满足return,并且该函数在遇到return 时才结束而没有循环。因此,该函数只给出-1,因为每个列表的第一个元素是10,它与110175 不匹配。

    这是我的修改。

    def LinearSearch(arr, n):
    
        count = 0
        for i in arr:
            if i == n: return count
            else: count += 1
        return -1    
    
    def main():
    
        arr1 = [10, 20, 80, 30, 60, 50, 110, 100, 130, 170]
        n1 = 110
    
        arr2 = [10, 20, 80, 30, 60, 50, 110, 100, 130, 170]
        n2 = 175
    
        result1 = LinearSearch(arr1, n1)
        if result1 != -1: print('Item %d found at index %d' % (n1, result1))
        else: print('Item not found')
    
        result2 = LinearSearch(arr2, n2)
        if result2 != -1: print('Item %d found at index %d' % (n2, result2))
        else: print('Item not found')
    
    main()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多