我是python的新手,我們被賦予創建一個不使用「in」或索引的線性搜索程序的任務。該程序編譯但是說我輸入的每個數字都不在列表中。我還必須爲二分查找做同樣的事情,但我一次只做一件事情。任何幫助表示讚賞!線性搜索Python
PS:如何在不使用「索引」功能的情況下顯示它的索引?
def linearSearch(intList,target):
found = False
position = 0
while position < len(intList) and not found:
if intList[position] == target:
found = True
position = position + 1
return found
linearList = [3,5,9,7,6,12,15,9,1]
numInput = input("What number are you looking for? ")
numFound = linearSearch(numInput, linearList)
if numFound:
print("The number is in index: ")
else:
print("The number is not in the list")
這是一個提示,以解決您的問題:輸入是字符串類型,並且您將其與整數進行比較 – karthikr