简体   繁体   English

如何有效地简化代码?

[英]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, 因此,目前我的工作分配问题是,分配问题为:定义print_most_frequent()函数,该函数传递了两个参数,一个包含单词及其对应频率(在文本字符串中出现的次数)的字典,例如,

{"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 所以,现在如果您想要9位数字的单词,只需说

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: 当您只循环一次频率时,这会更快,但是如果您仍然需要一个函数,则可以只做一个线性lambda:

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']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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