python编程中的线性搜索

时间:2017-09-10 16:42:36

标签: python

我已经用python语言编写了一个线性搜索代码。该代码适用于单个数字的数字,但它不适用于双位数字或更多数字。这是我的代码。

def linear_search(x,sort_lst):
    i = 0
    c= 0
    for i in range(len(sort_lst)):
        if sort_lst[i] == x :
             c= c+1
    if (c > 0):
      print ("item found")
    else : 
      print ("not found")
sort_lst= input("enter an array of numbers:")
item= input("enter the number to searched :")
linear_search(item,sort_lst)

有什么建议吗?

3 个答案:

答案 0 :(得分:0)

替换

sort_lst= input("enter an array of numbers:")

使用:

print 'enter an array of numbers:'
sort_lst= map(int, raw_input().strip().split(' '))

答案 1 :(得分:0)

如果你想要的只是一个子字符串搜索,你可以使用这个

print("item found" if x in sort_lst else "not found")

如果您想要变得更复杂,那么您需要将输入从字符串转换为实际列表。

(假设空格分隔值)

sort_lst= input("enter an array of numbers:").split()

然后,这实际上是一个字符串列表,而不是整数,但只要你将字符串与字符串进行比较,那么你的逻辑应该可以工作

注意:上述打印语句在两种情况下仍然有效

答案 2 :(得分:0)

这可能是python 2.x和python 3.x中行为混淆的情况,作为input function has changed的行为。在python 2中,input如果输入(12, 34),则会生成元组12, 34。但是,在python 3中,这个相同的函数调用和输入产生"12, 34"。基于你print中的括号和你遇到的问题,你似乎很清楚你正在使用python 3: - )

因此,当您使用for i in range(len(sort_lst)):进行迭代,然后使用sort_lst[i]查找要匹配的元素时,您实际上是在查看字符串中的每个字符 "12, 34"(所以“1”,然后是“2”,然后是“,”,然后是“”等。)

要获得您所追求的行为,您首先需要将字符串转换为实际的数字列表(并将您匹配的输入转换为一串数字)。

假设您使用逗号分隔您输入的数字,您可以使用以下内容转换列表:

sorted_int_list = []
for number_string in sort_list.split(","):
    sorted_int_list = int(number_string.strip())

如果您熟悉列表推导,可以缩短为:

sorted_int_list = [int(number_string.strip()) for number_string in sort_list.spit(",")]

您还需要:

item = int(item.strip())

将你要比较的东西从字符串转换为int。

我假设你这样做是为了学习一些编程,而不仅仅是一些python,但是一旦你应用了上述转换,你实际上可以检查item是否在sorted_int_list中只需做:

is_found = item in sorted_int_list
if is_found:
    print ("Found it")
else:
    print ("Didn't find it :-(")

备注:

"12, 34".split(",")生成["12", " 34"],因为字符串上的split函数会将字符串分解为字符串列表,使用您传入其中的字符串在元素之间断开(在本例中, “”)。 See the docs

来自字符串末尾的

" 12 ".strip() trims whitespace