Vote Tally With Changed Minds
Implement a class VoteTally for a poll in which every voter backs at most one candidate at a time and may change their mind. Write these methods:
VoteTally()starts with no votes.vote(voter, candidate)records thatvoternow backscandidate. If the voter was backing another candidate, that vote moves tocandidate; if they already backcandidate, nothing changes. Returns the number of votescandidatehas afterwards.withdraw(voter)takes backvoter's vote. Returns the candidate who lost the vote, or""ifvoteris not backing anyone.votes_for(candidate)returns how many votescandidatehas now (0for a candidate nobody backs).find_leader()returns the candidate with the most votes. If several candidates share the most votes, it returns the one whose name comes first alphabetically. Returns""if no candidate has any votes.
The tests call the methods in sequence and compare every return value. The expected list holds null for the constructor.
Example 1
VoteTally()
vote("ann", "lee") returns 1
vote("bob", "kim") returns 1
find_leader() returns "kim"
vote("cat", "lee") returns 2
find_leader() returns "lee"
vote("ann", "kim") returns 2
votes_for("lee") returns 1
withdraw("bob") returns "kim"
find_leader() returns "kim"
withdraw("bob") returns ""
kim and lee tie at one vote and kim comes first alphabetically. When ann switches to kim, lee drops back to 1. After bob withdraws, kim and lee tie again at 1, and bob has nothing left to withdraw.
Constraints
voterandcandidateare1to8lowercase letters.- Each test makes
1to40method calls after the constructor.
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.