How to print the most frequent name (plurality)?

Viewed 63

I'm writing a plurality program in Python, letting voters vote for candidates and printing out the winner (most frequent name). I've managed to input the number of voters and their votes, but I can't seem to print out the winner. (It keeps printing out the least frequent.) And if you find any other errors, please correct them.

NB: This is a cs50 project. It was asked to be done in C, but I wanted to try it in Python.

from collections import Counter
#max = 9
candidates = ["Bob", "Steve", "Ross"]
for key in range(len(candidates)):
    print(candidates[key], end = " ")

v = []
voters = int(input("\nNumber of voters: "))
for i in range(voters):
    votes = input("Vote: ").capitalize()
    v.append(votes)
print(v)

vote_count = Counter(v)
print(vote_count)

max_votes = max(vote_count.keys())
print(max_votes) 
2 Answers

You can use Counter.most_common(1) to get the name with the most votes and their total number of votes. The 1 specifies that you only want the single most common name.

from collections import Counter

candidates = ["Bob", "Steve", "Ross"]

# Your user input would go here, I used a list for quick testing
votes = [
    "Ross",
    "Bob",
    "Steve",
    "Bob",
    "Bob",
    "Steve",
    "Steve",
    "Bob"
]

print(Counter(votes).most_common(1))

Output:

[('Bob', 4)]

max() on list or key of string will return the string with the highest value, ordered alphabetically.

In your case, Steve is always printed. So if you have Xavier in candidates or input, it will always printed Xavier using max(vote_count.key()) or max(vote_count) function.

To print most frequent name from vote_count you can use max with function list count as key:

max_votes = max(vote_count, key=v.count)
print(max_votes)

or get most frequent name from list v:

max_votes = max(v, key=v.count)
print(max_votes)

You also can iterate over the vote_count dict:

for candidate, voted in vote_count.items():
    if voted == max(vote_count.values()):
        max_votes = candidate
print(max_votes)

Or slicing most.common() index:

max_votes = vote_count.most_common(1)[0][0]
Related