python中的线性搜索代码

2024-04-30 03:51:57 发布

您现在位置:Python中文网/ 问答频道 /正文

这是线性搜索代码,但它不工作,谁能帮我!!在

data = []
n = int(raw_input('Enter how many elements you want: '))
for i in range(0, n):
    x = raw_input('Enter the numbers into the array: ')
    data.append(x)

print(data)

def lSearch(data, s):
    for j in range(len(data)):
        if data[j] == s:
            return j
    return -1

s = int(input('Enter the element do you want to search: '))
result = lSearch(data, s)

if result == -1:
    print("The Element is not found")
else:
    print("The element is an array at index %d",result) 

Tags: theinyouforinputdatarawrange
2条回答

s是一个整数,但由于您在列表中附加了x,因此它将充满字符串。在

x = raw_input('Enter the numbers into the array: ')

请看这里x是一个字符串。您还没有将其转换为int(与其他地方不同)


如果这实际上是python3而不是python2(正如它在标记中所说),那么您应该使用input()而不是{}(python3中实际上不存在原始输入)。input()将在python2中返回一个字符串(与python2不同,python2可能返回一个整数)。在

多亏了所有人。现在,我的代码是通过简单地将raw_input更改为input()来运行的。 数据=[]

n=int(input('输入需要的元素数:')

对于范围(0,n)内的i:

x = input('Enter the numbers into the array: ')

data.append(x)

k=已排序(数据)

打印(k)

定义lSearch(k,s):

^{pr2}$

s=int(input('输入要搜索的元素:')

结果=lSearch(k,s)

如果结果==-1:

print("The Element is not found")

其他:

print("The element is an array at index %d",result) 

相关问题 更多 >