该函数打印关键字长度,然后打印所需长度的所有字典关键字的排序列表,其中频率最高,频率最高。例如,以下代码:
for (int priority : pMap.keySet()) {
System.out.print(priority); //prints the priority
System.out.print(pMap.get(priority)); // prints the product for the priority
System.out.print(priceMap.get(priority)); //prints the price
System.out.println(); // changes the line
}
打印输出:
word_frequencies = {"fish":9, "parrot":8, "frog":9, "cat":9, "stork":1, "dog":4, "bat":9, "rat":4}
print_most_frequent(word_frequencies,3)
print_most_frequent(word_frequencies,4)
print_most_frequent(word_frequencies,5)
print_most_frequent(word_frequencies,6)
print_most_frequent(word_frequencies, 7)
到目前为止,我有这段代码:
3 letter keywords: ['bat', 'cat'] 9
4 letter keywords: ['fish', 'frog'] 9
5 letter keywords: ['stork'] 1
6 letter keywords: ['parrot'] 8
7 letter keywords: [] 0
这给了我:
def print_most_frequent(words_dict, word_len):
right_length = {}
for k, v in words_dict.items():
if len(k) == word_len:
right_length[k] = v
max_freq = max(right_length.values())
max_words = {}
for k, v in right_length.items():
if v == max_freq:
max_words[k] = v
print (str(word_len) + " letter keywords: " + str(sorted(max_words.keys())) + " " + str(max_freq))
但不是空序列。如何添加我的代码,以便计算空序列。
3 letter keywords: ['bat', 'cat'] 9
4 letter keywords: ['fish', 'frog'] 9
5 letter keywords: ['stork'] 1
6 letter keywords: ['parrot'] 8
答案 0 :(得分:1)
只需在max()
调用中添加一个回退条件,以便它永远不会尝试找到空的可迭代中的最大值:
max_freq = max(right_length.values() or [0])
如果right_length.values()
为空,则会使用[0]
(非空),而max()
不会产生错误。