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

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
  • 694
  • 3
  • 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,110
  • 8
  • 29