0

I am trying to find the maximum occurrences of a string in a list using Python my code currently is:

def count_occurences(input_string):
    list1 = []
    items = input_string.split(", ")

    for item in items:
        item = item.rstrip()

   
    max=0
    for i in items:
        
        count = input_string.count(i)
        if count > max:
            max = count
    

    for j in items:
        frequency = input_string.count(j)
        if frequency == max:
            list1.append(j)
            list1.append(max)
            

    return list1

  • 3
    What is the question here? – Holloway Oct 25 '21 at 08:23
  • Does this answer your question? [How can I count the occurrences of a list item?](https://stackoverflow.com/questions/2600191/how-can-i-count-the-occurrences-of-a-list-item) – alex Oct 25 '21 at 08:24
  • 1
    Note: `for item in items: item = item.rstrip()` actually does nothing. It won't alter the list elements. – Green绿色 Oct 25 '21 at 08:31

2 Answers2

0

Just one confusion is that your string variable is a string, not a list, which is what you asked about. This is what I came up with:

def count(a):
  dictionary={}
  for x in a:
    try:
      dictionary[x]+=1
    except Exception:
      dictionary[x]=1
  return (dictionary)
string = 'mary, bob, mary, bob, alex, julie'
s=string.split(",")
print(count(s))

You can access the count of each name by assigning it to a variable, and calling it like:

a=count(s)
s["bob"] #returns 2
Agent Biscutt
  • 712
  • 4
  • 17
0

Instead of writing your own algorithm, you could simply use the builtin Counter from collections package. This class is basically a dictionary with items as keys and frequencies as values:

from collections import Counter
string = 'mary, bob, mary, bob, alex, julie'
names = [name.strip() for name in string.split(', ')]
frequencies = Counter(names)
max_frequency = max(frequencies.values())
max_frequency_names = [name 
                       for name, frequency in frequencies.items() 
                       if frequency == max_frequency]
print(max_frequency_names)
Green绿色
  • 1,620
  • 1
  • 16
  • 43