2017-04-09 70 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