Home > Software design >  Mode of votes loop
Mode of votes loop

Time:02-22

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

CodePudding user response:

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 = [0, 0, 0, 0, 0]
for vote in votes:
    vote_count[vote - 1]  = 1  # Vote for 1 go to position 0, and so on
# `vote_count` will be equal to `[2, 2, 1, 0, 0]`

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

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

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

winning_values = [i for i in range(len(votes)) if vote_count[i - 1] == 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")

CodePudding user response:

You can use the mode function in the statistics module in python, for example:

from statistics import mode
A = [1, 2, 2, 3, 3 ,3]
print("Mode of List A is % s" % (mode(A)))

This function will raise the StatisticsError when the list is empty or when more than one mode is present.

  • Related