【问题标题】:How to search an infinite list of words in sorted order for an index corresponding to a word as input如何按排序顺序搜索无限的单词列表以查找与作为输入的单词对应的索引
【发布时间】:2020-04-09 15:39:49
【问题描述】:

我对我正在处理的给定流的一个难题感到困惑,我正在处理更好的线性时间O(n)..

按排序顺序在无限的单词列表中搜索与作为输入的单词对应的索引

给定一个无限列表["apple", "banana", "cat", "dog", ...] 我们有一个班级A 其中A.get(2) # => "cat" 编写一个函数来返回作为函数输入的单词的索引,如下所示:

A.get_index("cat") # => 2

你可以使用 A.get() 而不是 python 的 .index() 序列

【问题讨论】:

  • 按排序顺序搜索无限的单词列表。那么while循环?
  • 我假设你不想从 A.get_index() 中复制?
  • 在这里使用for 循环和enumerate 就足够了。
  • 你可以使用二分搜索
  • 你能在 O(N) 中展示你的尝试吗?

标签: python list algorithm stream


【解决方案1】:

IIUC,你可以在O(log n) 中通过对二分搜索的修改来做到这一点。

import bisect


def find(endless_haystack, needle):

    if endless_haystack[0] == needle:
        return 0

    i = 1
    hay = endless_haystack[i]
    while hay < needle:  # this is O(log n) where n is the index of the element
        i = 2 * i
        hay = endless_haystack[i]

    # from the loop before the element is between i and i // 2
    return bisect.bisect_left(endless_haystack, needle, i // 2, i)

请注意,上面的代码是一个实际解决方案的草图,您需要检查一些边缘情况。

【讨论】:

  • 如果无限列表不是无限的那么这是最好的+1
  • 我想你的意思是i = 0i = 2 * i
  • @EricSteen 更新了答案
【解决方案2】:

您可以使用为您提供索引和元素的内置函数enumerate

def get_index(word, my_infinite_list):
    return next(i for i, e in enumerate(my_infinite_list) if e == word)

内置函数next 将确保遍历您的列表,直到找到想要的单词

【讨论】:

  • 我不确定你是否可以在无限列表(或生成器)上使用枚举
  • 是的,你可以,这里是文档:docs.python.org/3/library/functions.html#enumerate
  • 并且OP在问题中显示了一个列表,可能是一个大列表,而不是一个无限列表,没有这样的东西:)
  • 另外 OP 说的是一个无限循环,但是如果你看一下不使用 list.index 的限制,在 o(n) 中显示一个例子是有意义的,这就是 list.index 的时间复杂度, OP可能会澄清他是否会展示他的尝试
【解决方案3】:

通过递增计数器来迭代列表,直到达到相应的值

class A:
   [...]


   def get_index(self, item):
       i = 0
       while self.get(i) != item:
           i += 1
       return i

注意:这不是很安全的代码。但是因为我们假设列表是无限的,所以您不会冒着超出索引的风险。但存在溢出风险...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多