R. Mercy R. Mercy - 1 year ago 68
Python Question

I need to assume for an empty sequence in this code for python

The function prints the keyword length, then prints a sorted list of all the dictionary keywords of the required length, which have the highest frequency, followed by the frequency. For example, the following code:

word_frequencies = {"fish":9, "parrot":8, "frog":9, "cat":9, "stork":1, "dog":4, "bat":9, "rat":4}

print_most_frequent(word_frequencies, 7)

prints outs:

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

So far I have this code:

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))

and this gives me:

3 letter keywords: ['bat', 'cat'] 9
4 letter keywords: ['fish', 'frog'] 9
5 letter keywords: ['stork'] 1
6 letter keywords: ['parrot'] 8

but not the empty sequence. How do I make an addition to my code so that it counts for the empty sequence.

7 letter keywords: [] 0

Answer Source

Simply add a fallback condition to the max() call so that it never tries to find the largest of an empty iterable:

max_freq = max(right_length.values() or [0])

If right_length.values() is empty, [0] (which is not empty) will be used instead, and max() doesn't produce an error for that.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download