2017-04-09 86 views
0

我是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") 
+0

這是一個提示,以解決您的問題:輸入是字符串類型,並且您將其與整數進行比較 – karthikr

回答

1

1)啓動position = -1

2)return position

3)你想position+=1if intList[position] == target:之前,你想break當你找到的元素。然後,您不需要found

東西被發現時linearSearch(linearList, numInput) > 0

然後,你的代碼是行不通的,因爲列表中包含整數,而input總是會返回一個字符串。您必須使用int(input(".."))

+0

感謝您的幫助!發佈後,我立即將輸入從字符串更正爲整數。我從while循環中獲得一個錯誤「,而位置 NacDan

+0

您已將'intList'分配給int。請自行調試您的代碼,請 –

+0

提示:您的參數順序爲1)列表2)編號查找 –

0
def linearSearch(intList,target): 
    #print (target) 
    found = False 
    position = 0 
    while position < len(intList): 
     #print(intList[position]) 
     if intList[position] == target: 
      found = True 
      break 
     position = position + 1 

    return found 

linearList = [3,5,9,7,6,12,15,9,1] 
numInput = int(input("What number are you looking for? ")) 
numFound = linearSearch(linearList,numInput) 
if numFound: 
    print("The number is in index: ") 
else: 
    print("The number is not in the list") 

請照顧類型轉換的...

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