由于某种原因,这个python线性搜索不起作用。每次我运行它并输入列表中的值时,它都不会告诉我该项目在列表中并且只是运行。 它不会给出任何语法错误,因此必须是符合逻辑的。有什么想法吗?
def linearSearch():
numbers = [3, 5, 54, 6, 17, 8, 32, 65, 87, 54]
pointer = 0
print("What would you like to search for?")
searchTerm = input()
try:
val = int(searchTerm)
except ValueError:
print("Please enter an integer")
linearSearch()
while pointer < len(numbers):
if numbers[pointer] == searchTerm:
print("Item has been found at " + pointer)
else:
pointer = pointer + 1
答案 0 :(得分:1)
if numbers[pointer] == searchTerm:
我想你打算写:
if numbers[pointer] == val:
searchTerm
是一个字符串(假设我们在Python 3.X中),因此它永远不会与列表中的任何整数进行比较。
其他问题:
"Item has been found at" + pointer
会崩溃。请尝试使用print("Item has been found at", pointer)
代替。pointer
。尝试在打印后添加break
。linearSearch()
。但是原始调用仍然在堆栈上,并且一旦内部调用完成将继续执行。然后它将与UnboundLocalError: local variable 'val' referenced before assignment
一起崩溃,因为val
从未在该上下文中成功创建。考虑一种非递归方法,例如:
def linearSearch():
numbers = [3, 5, 54, 6, 17, 8, 32, 65, 87, 54]
pointer = 0
print("What would you like to search for?")
while True:
try:
val = int(input())
break
except ValueError:
print("Please enter an integer")
while pointer < len(numbers):
if numbers[pointer] == val:
print("Item has been found at", pointer)
break
else:
pointer = pointer + 1
linearSearch()
答案 1 :(得分:1)
您应该使用val
这是一个int而不是searchTerm
,当您与numbers[pointer]
进行比较时,这是一个字符串。
另外,不要忘记打破你的循环,否则它将无限期地运行!
if numbers[pointer] == val:
print("Item has been found at " + str(pointer))
break
编辑还添加了str(pointer)
,因为当您尝试使用字符串添加int时,它会在Python3 +中引发错误。
答案 2 :(得分:0)
线性搜索:
// funtion which rturns true if item found inside list.
def linearSearch(list, value):
for i in range(len(list)):
if i == value:
return True
//调用上面的函数传递值列表和要搜索的项目
list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
item = 10
print(linearSearch(list, item)) // item to search