代码之家  ›  专栏  ›  技术社区  ›  data-oil

在字符串列表中搜索的高效快捷方法

  •  3
  • data-oil  · 技术社区  · 7 年前

    以下函数返回列表中包含与输入的单词完全相同字符的单词数。单词中字符的顺序并不重要。然而,假设有一个包含数百万单词的列表。执行此搜索最有效、最快的方法是什么?

    示例:

    words_list = ['yek','lion','eky','ekky','kkey','opt'];
    

    如果要将单词“key”与列表中的单词进行匹配,则函数只返回“yek”和“eky”,因为它们与“key”共享相同的字符,而不考虑顺序。

    下面是我编写的函数

    def find_a4(words_list, word):
        # all possible permutations of the word that we are looking for
        # it's a set of words 
        word_permutations = set([''.join(p) for p in permutations(word)])
        word_size = len(word)
        count = 0
    
        for word in word_list:
            # in the case of word "key", 
            # we only accept words that have 3 characters 
            # and they are in the word_permutations 
            if len(word) == word_size and word in word_permutations:
                count += 1
    
        return count
    
    2 回复  |  直到 7 年前
        1
  •  4
  •   fferri    7 年前

    一种字典,其关键字是单词的排序版本:

    word_list = ['yek','lion','eky','ekky','kkey','opt']
    
    from collections import defaultdict
    word_index = defaultdict(set)
    
    for word in word_list:
        idx = tuple(sorted(word))
        word_index[idx].add(word)
    
    # word_index = {
    #    ('e', 'k', 'y'): {'yek', 'eky'},
    #    ('i', 'l', 'n', 'o'): {'lion'},
    #    ('e', 'k', 'k', 'y'): {'kkey', 'ekky'},
    #    ('o', 'p', 't'): {'opt'}
    # }
    

    然后进行查询:

    def find_a4(word_index, word):
        idx = tuple(sorted(word))
        return len(word_index[idx])
    

    或者,如果需要返回实际单词,请将其更改为 return word_index[idx]

    效率:查询运行 in average in O(1) time

        2
  •  2
  •   Aritesh    7 年前

    对于大字符串,您将有 n! 要搜索的置换。我将在比较之前对所有字符串进行排序,这将是nlog(n),并且仅在长度匹配时进行排序和比较-

    def find_a4(words_list, word):
        word = ''.join(sorted(word))
        word_size = len(word)
        count = 0
        for word1 in words_list:
            if len(word1) == word_size:
                if word == ''.join(sorted(word1)):
                    count += 1
        return count