Ballot Box
Project 1 cast me as the programmer for an electoral commission. Given a pile of ballots, work out who wins under three different counting rules, and check whether a ballot is a proper ranking in the first place.
My 2019 submission for this project was lost. These counters are rebuilt from the task description and checked against every worked example it gave, plus 300 seeded elections run through reference Python code.
- first_past_the_post()
- second_preference()
- multiple_preferences()
- is_valid_vote()
Input
Ballots
Thirteen voters, four candidates. Each counting scheme crowns someone different.
Best choice first, names separated by commas. Start a line with 3 x to repeat it.
- Ballots
- 13
- Candidates
- 4
- Majority
- 7
- alan
- guido
- ada
- grace
Results
The count
Same ballots, three different results. The counting rule matters as much as the votes.
Eliminate the lowest candidate, pass each of their ballots to its next choice still standing, and repeat until someone holds an absolute majority or only two remain.
Round 1
No one has a majority (7 needed). ada, grace, guido are tied on the fewest votes (3), so the alphabetically first goes. ada is eliminated with 3 votes, and each ballot moves to its next choice still standing.
- alan4
- ada3
- grace3
- guido3
Striped segments are transferred votes, coloured by the ballot's first choice.
adapasses on 3 ballots
Result
guido
>>> multiple_preferences(votes) # 13 ballots 'guido'
This made-up showcase was built to give 'guido': matches.
Question 4 · is_valid_vote
Is this a valid vote?
A valid instant-runoff ballot is a list that ranks every candidate exactly once and names nobody else. Type a vote as a Python value.
>>> is_valid_vote(['tom2', 'tom1', 'li'], ['tom1', 'li', 'tom2']) True
Every candidate is ranked exactly once.