这是线性搜索代码,但是没有人可以帮助我!
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)
答案 0 :(得分:4)
s
是一个整数,但是您的列表将填充字符串,因为您将x
附加到其中。
x = raw_input('Enter the numbers into the array: ')
请参见此处x
是一个字符串。你没有将它转换为int(与其他地方不同)
如果这实际上是Python 3而不是Python 2(正如你在标签中所说的那样),那么你应该使用input()
而不是raw_input()
(在Python 3中实际上并不存在raw_input)。 input()
将在Python 3中返回一个字符串(与python2不同,它可能返回一个整数)。
答案 1 :(得分:-2)
感谢大家。现在,我的代码是通过简单的将raw_input更改为input()来运行的。 data = []
n = int(输入('输入您想要的元素数量:'))
表示范围(0,n)中的i:
x = input('Enter the numbers into the array: ')
data.append(x)
k =已排序(数据)
打印(k)的
def lSearch(k,s):
for j in range(len(k)):
if k[j] == s:
return j
return -1
s = int(输入('输入要搜索的元素:'))
result = lSearch(k,s)
如果结果== -1:
print("The Element is not found")
否则:
print("The element is an array at index %d",result)