+ 2
My question is, i have a list of words, and i want to output the word which has maximum or minmum frequency?
8 Antworten
+ 8
max(words, key=words.count)
+ 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.
+ 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
+ 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.
+ 2
Thanks, but i got solution
+ 1
Any other method, without using buil in function?
+ 1
Yeah! I used this one
+ 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}")