【发布时间】:2017-09-10 20:02:40
【问题描述】:
嗨,我是 python 新手,这是我想要做的,我在下面列出了这个。
x= [1,2,3,4,5,6,7,8,9]
这是我的python代码:
length = len(x)
c = input("Enter a no\n")
for i in range (length):
if x[i] == c:
print ("Found at position ", i)
else:
print("not found")
输出正在接收。
Enter a no
2
not found
not found
not found
not found
not found
not found
not found
not found
not found
现在,根据我很少的知识,我发现这个多重未找到正在发生,因为每次循环都对列表进行不检查,如果它不可用,则由于缺少适当的 beak 而移动到其他部分声明 但是我无法弄清楚当它在 x[i] 中匹配时,它的输出应该是 Found at position 1 。我在某处读到需要使用if c in x[i],但它没有用。手头上我重写了代码。
def ls():
t = int(input("Enter your search no \n"))
for i in x:
if i!= t:
continue
print("Your value is present in ")
break
else:
print ("parrrrrrrrrrr")
ls()
这一切都很好。如果我能了解这将有所帮助:
- 对于第一个程序,为什么即使列表中存在输入也找不到它的显示
- c in x[i] 的输入部分发生了同样的问题,据我所知 (现在没有意义) 它也应该可以工作
- 如果是整数与列表的情况,那么我的第二个代码是如何工作的 - 这是进行线性搜索的正确方法吗?
【问题讨论】:
-
问题在于您尝试将
str()与int()进行比较。线性搜索有 O(n),但如果你的列表是排序的,你可以使用 bisect 和 O(log n)。 -
wtf:我忘了输入需要一个字符串,非常感谢,是否有任何链接可以解释 o(n) 细节。谢谢@VadymStupakov
-
只需输入谷歌
big o notation
标签: python linear-search