线性搜索算法部分正确

huangapple go评论124阅读模式
英文:

Linear search algorithm partially correct

问题

Here's the translated code portion:

def linsearch(list, target):
    for i in range(0, len(list)):
        if (list[i] == target):
            return (i)
        else:
            return ("not in list")

list1 = [1, 2, 3, 4, 5]

print(linsearch(list1, 1))

Please note that the code you provided has an issue. It will return "not in list" as soon as it encounters the first element that doesn't match the target, which might not be the intended behavior. If you want to check all elements before concluding that the target is not in the list, you should remove the else statement.

英文:
def linsearch(list, target):
    for i in range(0, len(list)):
            if (list[i] == target):
                return (i)
            else:
                return ("not in list")

list1 = [1,2,3,4,5]

print(linsearch(list1,1))

This is the python program.
Whenever I put target as 1 it returns correct index that is 0, but for all other cases it gives the else case prompt i.e. "not in list"

答案1

得分: 1

You should not return inside the else statement. If you have a return in both the if and the else, you will never proceed to the second iteration of your for loop.

You can instead just omit the else completely and just do nothing when list[i] does not match your target. And only when your code reaches the end of the for loop without returning on a match, return the "not in list" value.

def linsearch(list, target):
    for i in range(0, len(list)):
        if (list[i] == target):
            return (i)
    return ("not in list")
英文:

You sohuld not return inside the else statement. If you have a return in both the if and the else, you will never proceed to the second iteration of your for loop.

You can instead just ommit the else completely and just do nothing when list[i] does not match your target. And only when your code reaches the ent of the for loop without returning on a match, return the "not in list" value.

def linsearch(list, target):
    for i in range(0, len(list)):
        if (list[i] == target):
            return (i)
    return ("not in list")

huangapple
  • 本文由 发表于 2023年7月6日 21:41:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76629485.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定