You are given ranked ballots in aggregated form. Each key is an ordered tuple of candidate names representing one voter's preference from highest to lowest, and each value is the number of voters who submitted that exact ranking.
Implement two methods:
-
popular_vote(ballots) -> candidate
-
Return the candidate with the largest number of first-place votes.
-
ranked_choice_winner(ballots) -> candidate
-
In each round, count only the highest-ranked non-eliminated candidate on each ballot.
-
If any candidate has more than 50% of the active first-place votes, return that candidate.
-
Otherwise, eliminate the candidate with the fewest first-place votes and recount.
-
Continue until a candidate has a majority or only one candidate remains.
Assumptions:
-
Every ballot ranks the same set of candidates.
-
There is no tie when choosing which candidate to eliminate.
Example input:
ballots = {
("A", "B", "C"): 4,
("B", "C", "A"): 3,
("C", "B", "A"): 2
}
For this example:
-
The popular-vote winner is
A
, because
A
has the most first-place votes initially.
-
The ranked-choice winner is
B
: first-round counts are
A=4, B=3, C=2
; eliminate
C
, then
C
's ballots transfer to
B
, so
B
becomes
5
out of
9
.