简体   繁体   中英

How can I simplify my code in an efficient way?

so currently im stuck on a question of my assignment, the assignment question is: Define the print_most_frequent() function which is passed two parameters, a dictionary containing words and their corresponding frequencies (how many times they occurred in a string of text), eg,

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

and, an integer, the length of the keywords in the dictionary which are to be considered.

The function prints the keyword length, followed by " letter keywords: ", 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,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) 

prints the following:

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

I have coded to get the answer above however it is saying I'm wrong. Maybe it needs a simplifying but i'm struggling how to. Could someone help thank you.

def print_most_frequent(words_dict, word_len):
    word_list = []
    freq_list = []
    for word,freq in words_dict.items():
        if len(word) == word_len:
            word_list += [word]
            freq_list += [freq]
    new_list1 = []
    new_list2 = []
    if word_list == [] and freq_list == []:
        new_list1 += []
        new_list2 += [0]
        return print(new_list1, max(new_list2))
    else:
        maximum_value = max(freq_list)
        for i in range(len(freq_list)):
            if freq_list[i] == maximum_value:
                new_list1 += [word_list[i]]
                new_list2 += [freq_list[i]]
                new_list1.sort()
        return print(new_list1, max(new_list2))

You can use:

def print_most_frequent(words_dict, word_len):
    max_freq = 0
    words = list()
    for word, frequency in words_dict.items():
        if len(word) == word_len:
            if frequency > max_freq:
                max_freq = frequency
                words = [word]
            elif frequency == max_freq:
                words.append(word)
    print("{} letter keywords:".format(word_len), sorted(words), max_freq)

It just iterates over the words dictionary, considering only the words whose length is the wanted one and builds the list of the most frequent words, resetting it as soon as a greater frequency is found.

One way you can do is to map the values as keys and vice-versa, this way you can easily get the most frequent words:

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

getfunc = lambda x, dct: [i for i in dct if dct[i] == x]
new_dict = { k : getfunc(k, a) for k in a.values() }

print (new_dict)

output:

{8: ['parrot'], 1: ['stork'], 4: ['rat', 'dog'], 9: ['bat', 'fish', 'frog', 'cat']}

So, now if you want 9 digit words, simply say

b = new_dict[9]
print (b, len(b))

which will give:

['cat', 'fish', 'bat', 'frog'] 4

You get to use the dictionary, instead of calling the function again and over. This is faster as you loop over the frequencies just once, but if you still need a function, can just do a one-liner lambda maybe:

print_most_frequent = lambda freq, x: print (freq[x])

print_most_frequent(new_dict, 9)
print_most_frequent(new_dict, 4)

which gives:

['fish', 'bat', 'frog', 'cat']
['rat', 'dog']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM