Jumble anagram最长的单词python
问题描述:
这个算法将输入一个数字,然后返回字典中有多少个字典从.txt
文件中获得该长度。我得到6783的输出,如果我输入5时,我应该根据我的列表获得5046。我不知道还有什么可以改变的。Jumble anagram最长的单词python
例如:5的输入应该回到5046
我也一直在试图通过列表与字长正整数的输入进行搜索,收集单词,字谜的最高金额,我不知道从哪里开始。
例如:用于字长度的4输入应该返回字谜这是6的最大数量,并输出字谜的列表中,例如
[’opts’, ’post’, ’pots’, ’spot’, ’stop’, ’tops’]
def maxword():
input_word = int(input("Enter word length (hit enter key to quit):"))
word_file = open("filename", "r")
word_list = {}
alist = []
for text in word_file:
simple_text = ''.join(sorted(text.strip()))
word_list.update({text.strip(): simple_text})
count = 0
for num in word_list.values():
if len(num) == input_word:
count += 1
alist.append(num)
return str(input_word) + str(len(alist))
答
这可以用来实现输入文本文件的单个传递。你的想法是将这个词排序并存储在地图中是正确的方法。
构建一个词典,其排序词作为关键词,因为它对于所有的词典和具有与关键词相同排序词的词列表都是相同的。
为了避免再次循环字典,我们将跟踪具有最大长度的键作为值。
如果建立这个word_list
字典是一次只用于特定的长度,那么你可以只考虑字典长度为input_word
的单词。
word_file = ["abcd", "cdab", "cdab", "cdab", "efgh", "ghfe", "fehg"]
word_list = {}
alist = []
input_word = 4
max_len = -1
max_word = ""
for text in word_file:
if len(text) == input_word:
simple_text = ''.join(sorted(text.strip()))
if simple_text not in word_list:
word_list.update({simple_text: [text.strip()]})
else:
word_list[simple_text].append(text.strip())
if(len(word_list[simple_text]) > max_len):
max_len = len(word_list[simple_text])
max_word = simple_text
print(max_word)
print(word_list[max_word])