Skip to content Skip to sidebar Skip to footer

Counting The Most Frequent Word In A List

I am trying to construct a program that if a user enters a name, it will return the number of people with that name. If they type 'most', it will return the name used the most. I g

Solution 1:

Well to count the number of times a name occurs that is specified by the user is pretty easy!

Let's write a little function to handle that and return the result.

names = ("billy","bob","pete","bob",'pete','bob');


def count_my_name(name):
    return ("The name %s occurs %s times." % (name,str(names.count(name))));

If we print this result with the name pete we would get the following result:

The name pete occurs 2 times.

Now for counting the most common name in the list, we can write another neat little function to handle that and return the result for us.

names = ("billy","bob","pete","bob",'pete','bob');
def get_most_common_name():
    all_names = set(names);
    most_common = max([names.count(i) for i in all_names]);
    for name in all_names:
        if names.count(name) == most_common:
            return ("The most common name is %s occuring a total of %s times." % (name,str(most_common)));

Which will give us the result: The most common name is bob occuring a total of 3 times.

Okay so now some explanation for our second function, what are we actually doing here?

Well first we grab our tuple named names, it has names in it but some of them are duplicates and we don't want to iterate over the same name multiple times. So make a new variable called all_names and make a set out of that list.

sets are usefull since they will remove any duplicates for us.

Now we can count the number of times a name occurs in names using:

most_common = max([names.count(i) for i in all_names]);

This gives us the number of the name that occurs the most inside our tuple. Which would be 3.

Now we simply just iterate over our set all_names and count how many times that name occurs in names.

If the name occurs as many times in names as our most_common variable we have the name that occurs the most.

Hope this helps!


Solution 2:

You can use a counter for this:

import collections

data = ('Billy Bob', 'Misty', …)
counts = collections.Counter(data)

# add an additional 'Misty'
counts.update(['Misty'])

# most seen name
if counts:
    name, count = counts.most_common(1)[0]
    print("most common name is {} with a count of {}".format(name, count))
else:
    print("no names available")

name = "Billy Bob"
count = counts.get(name)
if count is not None:
     print("There are {} people named {}".format(count, name))
else:
     print("There is no {}".format(name))

Post a Comment for "Counting The Most Frequent Word In A List"