Hey guys I am trying to write code for a problem and I am having trouble deducing how I am supposed to do this.
So I have to write code for the Instant Run-Off Vote or Alternative voting system. basically what happens is that there is a nested list where each list inside is a ballot with ranked votes. So for example if the list looks like: ['REPUBLICAN', 'DEMOCRATIC', 'GREEN'] this means that for this ballot, the first choice was republican, then democratic, and then green. So essentially in a nested list there are multiple ballots and the function would need to create a count for all the parties mentioned that will show for how many ballots was a specific party the first choice. If there are 6 ballots, for example, and for three or more of those Republican is the first choice, the function should end. If no party has a majority, then the party with the lowest votes is eliminated and you recount the ballots for which that party was the first choice but this time you count for the second choice. You keep doing this until you have a majority and return a dictionary with count for all parties (the count will be 0 if the parties will be eliminated but must be returned).
Here is an example:
>>> count_irv([[’REP’], [’DEM’, ’REP’, ’LIB’], [’GRN’,’REP’], [’GRN’], [’REP’, ’DEM’], [’LIB’, ’DEM’, ’REP’], [’LIB’, ’CON’], [’GRN’, ’DEM’], [’REP’]])
{’LIB’: 0, ’CON’: 0, ’DEM’: 0, ’GRN’: 3, ’REP’: 5}
This is the code that I have so far:
def count_irv(ballots)
count = {}
for list in ballots:
for element in list:
if element in count:
count[element] += 1
else:
count[element] = 1
for key in count:
if count[key] >= len(ballots):
return count
else:
count[last_place(count)] = 0
return count
Where the last_place
function simply returns the key in the dictionary with the lowest value.
Using the code above, for the example provided, the code returns:
{'REP': 6, 'DEM': 4, 'LIB': 3, 'GRN': 3, 'CON': 0}
So essentially what I need help with is figuring out how to make my code to keep looping until there is a party with majority votes.
Also, I am new on here and so far enjoying my experience. However someone reported my last post for not putting the code in the right way and I got banned for like a day, so I would appreciate if there is something I should be doing differently, please leave it the comments below and I will be sure to make appropriate edits and be considerate of it for my next post. Thanks!