使用python进行线性搜索

时间:2016-09-16 06:05:48

标签: python

您好我是python的新手,我试图通过在python中编写线性搜索来学习它,这里是代码,这是我到目前为止编写的代码。

a = [100]

n = int(raw_input("Enter the no. of elements: "))

print "Enter the elements: "
for i in range(0,n):
    print i

item = int(raw_input("Enter the item to be searched: "))

for i in range(0,10):

    if a[i] == item:
        print "Item ", item, "found at location", i+1
        break;

if i == n:
    print "Item", item, "not found"

我收到一个错误,说列表索引超出范围,我哪里错了?

3 个答案:

答案 0 :(得分:1)

列表中有一个元素。第二个外观尝试访问超出范围的元素1到9。

我建议使用enumerate,它返回(index,element)对,直到迭代的长度

for i, x in enumerate(a):
    if x == item:
        # found item at position i

如果要输入数字以生成元素列表,则

n = int(raw_input("Enter the no. of elements: "))
# build your list of n elements here 
for i in range(0,n):
    print i

例如,a = range(0, n)或导入random模块,如果您不想要线性数字范围

答案 1 :(得分:0)

您的代码中存在一些错误,我尝试重新排列它:

a = []

n = int(raw_input("Enter the no. of elements: "))

print "Enter the elements: "
for i in range(0,n):
    a.append(i)
    print (i)

item = int(raw_input("Enter the item to be searched: "))

found = False
for i in range(0,len(a)):
    if a[i] == item:
        found = True
        print "Item ", item, "found at location", i+1
        break;

if (not found):
    print "Item", item, "not found"

请注意以下几点:

  1. 使用列表而不是数组:a = []
  2. 使用列表操作:例如a.append(i)将元素插入第一个空闲插槽中的列表
  3. 使用布尔值
  4. 发现所有python功能;)

答案 2 :(得分:0)

略有不同(排序算法)

a = []

n = int(input("enter number of elements: "))

print("appending elements: ")

for i in range(0, n):
    a.append(i)
    print(i)

item = int(input("enter the item to be searched: "))
# for python2.x please use raw_input

for i in range(len(a)):
    print("searching...")
    if a[i] == item:
        print("found! at: %s" % i)
        break
    else:
        print("pretty bad day, nothing found!")