0

I have a list:

Fruit_list = ['apples','oranges','peaches','peaches','watermelon','oranges','watermelon']

Want to output:

print(most_frequent(Fruit_list))

which should print out "oranges"

I want to find the most frequnent string in the list. The 3 most frequent items are 'oranges','peaches','pears'. However, I want to select 'oranges' as 'o' is before 'p' and 'w' in the alphabet

4 Answers4

1
from collections import Counter

fruits = ['apples','oranges','peaches','peaches','watermelon','oranges','watermelon']

counter = Counter(fruits)

sorted_fruits = sorted(counter.items(), key=lambda tpl: (-tpl[1], tpl[0]))

print(sorted_fruits[0][0])

Output:

oranges
Paul M.
  • 10,481
  • 2
  • 9
  • 15
1

I think you're looking for a function like this:

def most_frequent(l):
    return max(sorted(l, key=str.lower), key=l.count)

Fruit_list = ['apples','oranges','peaches','peaches','watermelon','oranges','watermelon']
print(most_frequent(Fruit_list))  # outputs "oranges"

... if you don't want to use Counter.

To clarify:

  1. sorted(l, key=str.lower) sorts the list l lexicographically.

  2. max(<>, key=l.count) gets the mode of the sorted list.

Ryan Park
  • 65
  • 3
  • 9
0

did you try the following:

from collections import Counter
words = ['apples','oranges','peaches','peaches','watermelon','oranges','watermelon']
most_common_words= [word for word, word_count in Counter(words).most_common(3)]
most_common_words
Monica W
  • 27
  • 7
0
from collections import Counter

Fruit_list = ['apples','zranges','peaches','peaches','watermelon','zranges','watermelon']

max_counter = 0
min_ret = "z"
my_dict = dict(Counter(Fruit_list))


for items in my_dict.keys():
   if my_dict[items] > max_counter:
      max_counter = my_dict[items]
      min_ret = items

   if my_dict[items] == max_counter:
      if items < min_ret:
         min_ret = items

print(min_ret)

~