【问题标题】:Linear Search - Matching integer with list线性搜索 - 将整数与列表匹配
【发布时间】: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


【解决方案1】:
  1. 因为输入返回给你一个str对象,然后和int对象比较,没有隐式转换,所以表达式总是False
  2. c in x 其中 x 是一个列表,但 x[i] 在你的情况下是一个整数
  3. 第二个代码正在工作,因为您将输入隐式转换为int

我认为最优雅的方式是:

c = input("Enter a no\n")
items = [1,2,3]
print(items.index(int(c)) if int(c) in items else 'Not found')

如果输入不能转换为整数,当然不要忘记捕获 ValueError

【讨论】:

  • @SubhaSaha,我已经用更详细的解释更新了我的答案,
  • 感谢您的详细回答并提到价值点错误,我最近了解了错误处理的概念。 defthankyou(): @OlegRybalchenko :}
  • @SubhaSaha,不客气:)如果没有更多问题,请标记为答案)
  • 当然,没问题 :)
猜你喜欢
  • 2021-08-08
  • 1970-01-01
  • 2018-08-05
  • 2012-10-04
  • 1970-01-01
  • 1970-01-01
  • 2014-11-20
  • 2021-12-14
  • 2014-06-02
相关资源
最近更新 更多