英文:
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")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论