Instant Runoff Ballot Box
Implement a class BallotBox that counts ranked ballots by instant runoff. Write these methods:
BallotBox(candidates)sets up an election between the names incandidates, with no ballots yet.cast(ranking)adds a ballot that lists some of the candidates, from most to least preferred. Returns how many ballots have been cast.find_winner()counts all the ballots cast so far and returns the winner. The count runs in rounds. In each round every ballot goes to its highest-ranked candidate who is still in the race; a ballot whose candidates are all out goes to nobody. A candidate with more than half of the ballots that went to someone wins. Otherwise the candidate with the fewest ballots is knocked out (on a tie, the one that comes last incandidates) and the next round begins. Returns""if no ballot has been cast.rounds_needed()returns how many rounds that count takes, or0if no ballot has been cast.first_choices(name)returns how many ballots ranknamefirst.
The tests call the methods in sequence and compare every return value. The expected list holds null for the constructor.
Example 1
BallotBox(["ann","bob","cat"])
cast(["ann","bob"]) returns 1
cast(["bob"]) returns 2
cast(["cat","bob"]) returns 3
cast(["ann"]) returns 4
cast(["cat","ann"]) returns 5
find_winner() returns "ann"
rounds_needed() returns 3
first_choices("cat") returns 2
Round 1 gives ann 2, bob 1, cat 2, so bob is out and his own ballot has nobody left. Round 2 is a 2 to 2 tie; cat comes later in candidates, so cat is out. In round 3 ann has all 3 ballots that still count.
Constraints
2 <= len(candidates) <= 4, all differentrankingholds1or more different names fromcandidatesnameis one of the candidates- Each test makes
1to30method calls after the constructor.
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.