2017-10-28 56 views
2

這個算法將輸入一個數字,然後返回字典中有多少個字典從.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)) 

回答

0

這可以用來實現輸入文本文件的單個傳遞。你的想法是將這個詞排序並存儲在地圖中是正確的方法。

構建一個詞典,其排序詞作爲關鍵詞,因爲它對於所有的詞典和具有與關鍵詞相同排序詞的詞列表都是相同的。

爲了避免再次循環字典,我們將跟蹤具有最大長度的鍵作爲值。

如果建立這個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])