在python中查找用逗号运算符分隔的行中的字谜词
能够得到一行字谜,但想知道是否有更好的方法,以较低的复杂性解决上述问题。请帮助我计算上述方法的复杂性。这里最大的效率问题是在python中查找用逗号运算符分隔的行中的字谜词,python,Python,能够得到一行字谜,但想知道是否有更好的方法,以较低的复杂性解决上述问题。请帮助我计算上述方法的复杂性。这里最大的效率问题是如果对单词进行排序。计数(x)>1 让我们看一下这些部分。假设我们有N个元素,K个唯一元素,单词的平均长度是M 对列表中的每个元素进行排序,并将结果放入另一个列表中。这是每个元素的O(MlogM)时间,或者O(NMlogM)total 把这个新的列表列出来,它是O(N) 对于集合中的每个单词,对于列表中的每个单词,计算列表单词在列表中出现的次数。这才是关键。计算某个东西在列
如果对单词进行排序。计数(x)>1
让我们看一下这些部分。假设我们有N个元素,K个唯一元素,单词的平均长度是M
- 对列表中的每个元素进行排序,并将结果放入另一个列表中。这是每个元素的
时间,或者O(MlogM)
totalO(NMlogM)
- 把这个新的列表列出来,它是
O(N)
- 对于集合中的每个单词,对于列表中的每个单词,计算列表单词在列表中出现的次数。这才是关键。计算某个东西在列表中出现的次数需要花费
时间,而你要做O(N)
次,这就是KN
O(N^2*K)
- 对于集合中的每个单词,如果
计数>1,则迭代列表以查找所有匹配值。这是时间
只需将计数从列表中取出,就可以修复这个
O(N^2*K)
部分。让我们假设你这样做了,但没有解释到底是怎么做的(这很容易)。现在您的时间是O(NMlogM+N+NK)
。假设M尝试words=['aab','abb']
使用您的set
解决方案。@StefanPochmann:是的,在这种情况下,您需要的是多集而不是集合。我是在编辑的时候,当你评论的时候,你怎么用计数器做?它是不可散列的。
>>> line = "cat,ant,ate,abc,tan,act,tea"
>>> words = line.split(",")
>>> words
['cat', 'ant', 'ate', 'abc', 'tan', 'act', 'tea']
>>> sorted_words = map(tuple, [sorted(eachword) for eachword in words])
>>> sorted_words
[('a', 'c', 't'), ('a', 'n', 't'), ('a', 'e', 't'), ('a', 'b', 'c'), ('a', 'n', 't'), ('a', 'c', 't'), ('a', 'e', 't')]
>>> repeated_words = set(sorted_words)
>>> repeated_words
set([('a', 'b', 'c'), ('a', 'e', 't'), ('a', 'c', 't'), ('a', 'n', 't')])
>>> for repeated_word in repeated_words:
for index in [i for i, x in enumerate(sorted_words) if sorted_words.count(x) > 1 and x == repeated_word]:
print words[index],
print '\t'
ate tea
cat act
ant tan
>>> repeated_words = {}
>>> for word in words:
... sorted_word = tuple(sorted(word))
... repeated_words.setdefault(sorted_word, set()).add(word)
>>> repeated_words
{('a', 'b', 'c'): {'abc'},
('a', 'c', 't'): {'act', 'cat'},
('a', 'e', 't'): {'ate', 'tea'},
('a', 'n', 't'): {'ant', 'tan'}}
>>> for repeated_word, words in repeated_words.viewitems():
... if len(words) > 1:
... print(' '.join(words))
tea ate
act cat
ant tan
>>> repeated_words = {}
>>> for word in words:
... letter_set = frozenset(word)
... repeated_words.setdefault(letter_set, set()).add(word)
>>> repeated_words
{frozenset({'a', 'b', 'c'}): {'abc'},
frozenset({'a', 'e', 't'}): {'ate', 'tea'},
frozenset({'a', 'n', 't'}): {'ant', 'tan'},
frozenset({'a', 'c', 't'}): {'act', 'cat'}}
>>> for repeated_word, words in repeated_words.viewitems():
... if len(words) > 1:
... print(' '.join(words))
tea ate
ant tan
act cat