On this page
Cast Vote
TIP101 Unit 2 Session 2 (Click for link to problem statements)
U-nderstand
Understand what the interviewer is asking for by using test cases and questions about the problem.
- What are the inputs?
- A dictionary
votesthat maps each candidate to their vote count, and the name of thecandidatereceiving a vote.
- A dictionary
- What should the function return?
- The
votesdictionary, updated in place with one more vote forcandidate.
- The
- What if the candidate has no votes yet?
- Add them to the dictionary with 1 vote.
HAPPY CASE
Input: votes = {"Alice": 2, "Bob": 1}, candidate = "Alice"
Output: {"Alice": 3, "Bob": 1}
Explanation: Alice already has 2 votes, so her count goes up to 3.
EDGE CASE
Input: votes = {}, candidate = "Carol"
Output: {"Carol": 1}
Explanation: Carol is not in the dictionary yet, so she is added with 1 vote.
P-lan
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Check if the candidate is already in the dictionary, add them if not, then increment their votes by 1.
1) If the candidate is a key in the dict, increment the value by 1
2) Otherwise, map candidate -> 1 in the dict
I-mplement
def cast_vote(votes, candidate):
if candidate in votes:
votes[candidate] += 1
else:
votes[candidate] = 1
return votes
Alternative Solution
def cast_vote(votes, candidate):
if candidate not in votes:
votes[candidate] = 0
votes[candidate] += 1
return votes