My question is, i have a list of words, and i want to output the word which has maximum or minmum frequency? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

My question is, i have a list of words, and i want to output the word which has maximum or minmum frequency?

31st Dec 2022, 7:40 AM
Rupesh Bhusare
Rupesh Bhusare - avatar
8 Answers
+ 8
max(words, key=words.count)
31st Dec 2022, 3:09 PM
HonFu
HonFu - avatar
+ 9
Rupesh Bhusare , if you like to get more detailed help, we need to see your attempt here. please link your code here. hint: > we can use a dictionary as a counter, and run a for loop to iterate over the words list, updating the dict with numbers. > to get the word with the max / min frequency, we can use max() / min() function, by also applying a short lambda function to each. it needs just 6 lines of code to get everything done. > an other possible solution is using the words list and the count() function.
31st Dec 2022, 12:13 PM
Lothar
Lothar - avatar
+ 3
You can use the Counter data type which can do exactly this. from collections import Counter frequencies = Counter(list_of_words) print(frequencies.most_common()[0]) # max print(frequencies.most_common()[-1]) # min
31st Dec 2022, 7:43 AM
Tibor Santa
Tibor Santa - avatar
+ 2
Surely there are lots of ways to approach the same problem. You could also write the code in Assembly. Or write down the words on little pieces of paper, and organize them on the table. It's up to you, if you use the tools offered by the standard language, or you want to reinvent the wheel and write your own solutions. If you want a very simple one, you can write a for loop to go through all words, and keep track of the shortest and longest words found so far, in separate variables.
31st Dec 2022, 9:53 AM
Tibor Santa
Tibor Santa - avatar
+ 2
Thanks, but i got solution
31st Dec 2022, 12:20 PM
Rupesh Bhusare
Rupesh Bhusare - avatar
+ 1
Any other method, without using buil in function?
31st Dec 2022, 9:20 AM
Rupesh Bhusare
Rupesh Bhusare - avatar
+ 1
Yeah! I used this one
31st Dec 2022, 3:53 PM
Rupesh Bhusare
Rupesh Bhusare - avatar
+ 1
words = ['cat', 'dog', 'cat', 'fish', 'dog', 'dog'] # Create a dictionary to store the frequency of each word word_freq = {} # Iterate over the list of words and update the frequency for each word for word in words: if word in word_freq: word_freq[word] += 1 else: word_freq[word] = 1 # Find the word with the maximum frequency max_word = None max_freq = 0 for word, freq in word_freq.items(): if freq > max_freq: max_word = word max_freq = freq print(f"The word with the maximum frequency is {max_word} with a frequency of {max_freq}")
2nd Jan 2023, 5:03 AM
Roberth Alejandro Pupiales Cruz
Roberth Alejandro Pupiales Cruz - avatar