我試圖寫一個程序,它有兩個功能:文本查找前5個字長
count_word_lengths這需要論證文本,文本字符串,並返回一個默認詞典記錄每個詞長度的計數。一個例子調用此函數:
top5_lengths這需要相同的參數文本並返回前5字長的列表。
注意:在 兩種長度具有相同的頻率的情況下,就應該按降序排列。另外,如果長度少於5個字符,它應該返回一個較短的排序字長度列表。
實例調用count_word_lengths:
count_word_lengths("one one was a racehorse two two was one too"):
defaultdict(<class 'int'>, {1: 1, 3: 8, 9: 1})
實例調用top5_lengths:
top5_lengths("one one was a racehorse two two was one too")
[3, 9, 1]
top5_lengths("feather feather feather chicken feather")
[7]
top5_lengths("the swift green fox jumped over a cool cat")
[3, 5, 4, 6, 1]
我當前的代碼是這樣的,而且似乎輸出所有這些電話,但它是失敗的一個隱藏的測試。我沒有考慮什麼類型的輸入?我的代碼的行爲是否正確?如果沒有,我該如何解決這個問題?
from collections import defaultdict
length_tally = defaultdict(int)
final_list = []
def count_word_lengths(text):
words = text.split(' ')
for word in words:
length_tally[len(word)] += 1
return length_tally
def top5_word_lengths(text):
frequencies = count_word_lengths(text)
list_of_frequencies = frequencies.items()
flipped = [(t[1], t[0]) for t in list_of_frequencies]
sorted_flipped = sorted(flipped)
reversed_sorted_flipped = sorted_flipped[::-1]
for item in reversed_sorted_flipped:
final_list.append(item[1])
return final_list