Mode of votes loop

Viewed 56

I'm facing a problem with an game that i'm working on. In this game, players need to choose a number and vote. So let's say that 5 players are playing, when they vote and the votation ends, the game returns the mode of the votes. I can get the mode with max(set(int_list), key=int_list.count) where int_list is a list that i'm using to store the votes.

But if the votes list is something like [1,1,2,2,3] or [1,1,2,2] I get 1 as the mode, but I'd like a condition to check theses cases and return a message "inconclusive mode" or something like that.

The mode is the value that appears most often in a set of data values.

How can i make this condition? I'm using Python btw

3 Answers

We can use a couple of for loops for this, since your list is so short. Let us assume that the votes were casted as:

votes = [1, 1, 2, 2, 3]

First, count the votes by accumulating the count in each "bin":

vote_count = dict()
for vote in votes:
    if vote not in vote_count:
        vote_count[vote] = 0
    vote_count[vote] += 1  # Vote for 1 go to position 0, and so on
# `vote_count` will be equal to `{1: 2, 2: 2, 3: 1}`

Then, find the maximum number of votes that any option received:

max_votes = max(vote_count.values())
# `max_votes` will be equal to `2`

Finally, find all the options that got that number of votes:

winning_values = [vote for vote, n in vote_count.items() if n == max_votes]
# Remember, votes for 1 were on position 0

You can check if a tie happened with this condition:

if len(winning_values) > 1:
    print("There was a tie")

The Counter class from collections is very useful for this.

from collections import Counter

votes = [1, 1, 2, 2, 3]

(a,count1),(_,count2) = Counter(votes).most_common(2)
if count1 == count2:
    print("inconclusive mode")
else:
    print("mode is",a)

It also has the advantage that it is also very fast at what it does (counting things).

The standard library has statistics.multimode, which can be used in your case:

try:
    mode, = statistics.multimode(int_list)
except ValueError:
    print('inconclusive mode')
else:
    print(mode)

It also has statistics.mode, which returns the first mode like the code you showed us (except in linear rather than quadratic time).

Related