[英]How to find anagrams using 3 words in a text having a list of words?
我有一个文本和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')
天真的算法是:
(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 (nk) k^(nk)
为界。 因此,找到k个组中n个元素的所有分区具有O(n^k * k^(nk))
复杂度。
让我们尝试在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(" ")
并建立一个dict 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())
在dict中将已排序的字母组作为字符串进行搜索,并返回一组单词或一个空集(如果不匹配)。 itertools.product(*L)
创建找到的集合的笛卡尔积。 如果有一个空集(没有匹配项的组),那么根据定义,该产品为空。 Ouput(有重复的原因,请尝试查找!):
('nego', 'mal', 'toni')
('mal', 'nego', 'toni')
('mal', 'nego', 'toni')
('mal', 'nego', 'toni')
在这里重要的是,单词的数量不再是问题(字典中的查找将摊销O(1)
),但是要搜索的文本的长度可能变为1。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.