我正在尝试搜索某个项目,但程序给出的结果不正确

I'm trying to search an item but the program gives incorrect result

我在 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()

我希望第一次搜索的结果是 'Element x is present at index 6',但结果是 'Item not found'。

因为你的 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()