如何在具有单词列表的文本中使用3个单词来找到字谜?

时间:2019-07-11 10:46:34

标签: python string list

我有一个文本和6万个单词的列表。 我需要使用3个单词(以字母顺序最后一个)从单词列表中找到文本的字谜,并且该函数应返回3个单词的元组,以建立给定文本的字谜。 注意:我必须忽略文本中的大写字母和空格。

我开发了一种功能,可以查找文本中包含的单词列表中的所有单词。 但我不知道该如何结束字谜。

   def es3(words_list, text):
        text=text.replace(" ","")
        for x in text:
        text=text.replace(x,x.lower())

        result=[]
        cont=0
        for x in words_list:
            if len(x)>=2:
                for c in x:
                    if c in text:
                        cont+=1
                        if cont==len(x):
                            result.append(x)
            cont=0


           Examples:
          text =   "Andrea Sterbini"  -> anagram= ('treni', 'sia', 'brande')
            sorted(andreasterbini)==sorted(treni+sia+brande) 


            "Angelo Monti"          -> ('toni', 'nego', 'mal')
            "Angelo Spognardi"      -> ('sragion', 'pend', 'lago')
            "Ha da veni Baffone"    -> ('video', 'beh', 'affanna')

1 个答案:

答案 0 :(得分:0)

天真的算法是:

  • 获取单词的每个三元组,然后将项(sorted letters of the three words, triplet)添加到多图(每个键可能接受多个值的映射:在Python中,为正则映射key -> [values])。
  • 对搜索到的文本的字母进行排序,并在多图中输出相关的值。

问题在于多图的构造具有O(N^3)的时间和空间复杂度。如果N = 60,000,则您有21.6万亿个运算和值。好多!

让我们尝试减少这种情况。让我重新讨论这个问题:给定一个序列,找到三个子序列:1.不重叠并且覆盖该序列; 2.在给定的集合中。参见第一个示例:“ Angelo Monti”->(“ toni”,“ nego”,“ mal”)

sequence    a e g i l m n n o o t
subseq1           i     n   o   t
subseq2       e g         n   o
subseq3     a       l m

查找覆盖该序列的三个非重叠子序列与将k个组中的n个元素进行分区的问题相同。复杂度称为S(n, k),受1/2 (n k) k^(n-k)限制。因此,找到k个组中n个元素的所有分区具有O(n^k * k^(n-k))的复杂性。

让我们尝试在Python中实现这一点:

def partitions(S, k):
    if len(S) < k: # can't partition if there are not enough elements
        raise ValueError()
    elif k == 1:
        yield tuple([S]) # one group: return the set
    elif len(S) == k:
        yield tuple(map(list, S)) # ([e1], ..., [e[n]])
    else:
        e, *M = S # extract the first element
        for p in partitions(M, k-1): # we need k-1 groups because...
            yield ([e], *p) # the first element is a group on itself
        for p in partitions(M, k):
            for i in range(len(p)): # add the first element to every group
                yield tuple(list(p[:i]) + [[e] + p[i]] + list(p[i+1:]))

一个简单的测试:

>>> list(partitions("abcd", 3))
[(['a'], ['b'], ['c', 'd']), (['a'], ['b', 'c'], ['d']), (['a'], ['c'], ['b', 'd']), (['a', 'b'], ['c'], ['d']), (['b'], ['a', 'c'], ['d']), (['b'], ['c'], ['a', 'd'])]

现在,我将使用您在问题中使用的一些单词作为单词列表:

words = "i have a text and a list of words i need to find anagrams of the text from the list of words using words lasts in alphabetic order and the function should return a tuple of the words that build an anagram of the given text note i have to ignore capital letters and spaces that are in the text i have developed the function that finds all the words of the list of words that are contained in the text but i dont know how to end finding the anagrams and some examples treni sia brande toni nego mal sragion pend lago video beh affanna".split(" ")

并构建字典sorted(letters) -> list of words来检查组

word_by_sorted = {}
for w in words:
    word_by_sorted.setdefault("".join(sorted(w)), set()).add(w)

结果是:

>>> word_by_sorted
{'i': {'i'}, 'aehv': {'have'}, 'a': {'a'}, 'ettx': {'text'}, 'adn': {'and'}, 'ilst': {'list'}, 'fo': {'of'}, 'dorsw': {'words'}, 'deen': {'need'}, 'ot': {'to'}, 'dfin': {'find'}, 'aaagmnrs': {'anagrams'}, 'eht': {'the'}, 'fmor': {'from'}, 'ginsu': {'using'}, 'alsst': {'lasts'}, 'in': {'in'}, 'aabcehilpt': {'alphabetic'}, 'deorr': {'order'}, 'cfinnotu': {'function'}, 'dhlosu': {'should'}, 'enrrtu': {'return'}, 'elptu': {'tuple'}, 'ahtt': {'that'}, 'bdilu': {'build'}, 'an': {'an'}, 'aaagmnr': {'anagram'}, 'eginv': {'given'}, 'enot': {'note'}, 'eginor': {'ignore'}, 'aacilpt': {'capital'}, 'eelrstt': {'letters'}, 'acepss': {'spaces'}, 'aer': {'are'}, 'ddeeelopv': {'developed'}, 'dfins': {'finds'}, 'all': {'all'}, 'acdeinnot': {'contained'}, 'btu': {'but'}, 'dnot': {'dont'}, 'know': {'know'}, 'how': {'how'}, 'den': {'end'}, 'dfgiinn': {'finding'}, 'emos': {'some'}, 'aeelmpsx': {'examples'}, 'einrt': {'treni'}, 'ais': {'sia'}, 'abdenr': {'brande'}, 'inot': {'toni'}, 'egno': {'nego'}, 'alm': {'mal'}, 'aginors': {'sragion'}, 'denp': {'pend'}, 'aglo': {'lago'}, 'deiov': {'video'}, 'beh': {'beh'}, 'aaaffnn': {'affanna'}}

现在,将砖块放在一起:如果text的每个分区分为三组,并且如果这三组是列表中单词的字谜,则输出单词:

for p in partitions("angelomonti", 3):
    L = [word_by_sorted.get("".join(sorted(xs)), set()) for xs in p]
    for anagrams in itertools.product(*L):
        print (anagrams)

备注:

  • word_by_sorted.get("".join(sorted(xs)), set())在字典中搜索作为字符串的字母排序组,如果没有匹配项,则返回一个单词集或一个空集
  • itertools.product(*L)创建找到的集合的笛卡尔积。如果有一个空集(没有匹配项的组),那么根据定义,该产品为空。

输出(有重复的原因,请尝试找到它!)

('nego', 'mal', 'toni')
('mal', 'nego', 'toni')
('mal', 'nego', 'toni')
('mal', 'nego', 'toni')

这里重要的是,单词的数量不再是问题(字典中的查找将摊销O(1)),但是要搜索的文本长度可能变成一个。