嗨,这是我的第一篇文章。我创建了我的程序,以便以递减的大小打印所有字谜。然而,它还打印了所有左边的单词,这些单词没有我不想要它做的字谜。我也想知道是否有更有效的方法可以做到这一点,因为我的方式似乎相当迂回。请帮忙!
import time
start_time = time.time()
def wordIterator(dictionaryFilename):
with open(dictionaryFilename,'r') as f:
for line in f:
word = line.strip()
yield word
def largestAnagram(words):
import collections
d = collections.defaultdict(list)
for word in words:
sortedWord = str(sorted(word))
d[ hash(sortedWord) ].append(word)
maxKey = max( d.keys(), key = lambda k : len(d[k]) )
while (maxKey != 0):
maxKey = max( d.keys(), key = lambda k : len(d[k]) )
print(d[maxKey])
del d[maxKey]
return d[maxKey]
ter = wordIterator( 'dictionary.txt' )
print largestAnagram(ter)
end_time = time.time()
print("Elapsed time was %g seconds" %(end_time-start_time))
答案 0 :(得分:0)
我想你想要while (maxKey > 1)
。
但是你的算法有不必要的二次复杂度,效率更高 解决方案是:
# ...
keys = [(len(v), k) for k, v in d.items() if len(v) > 1]
keys.sort(reverse=True)
for _, k in keys:
print(d[k])