Best Set - codepath/compsci_guides GitHub Wiki
Unit 2 Session 1 (Click for link to problem statements)
U-nderstand
Understand what the interviewer is asking for by using test cases and questions about the problem.
-
Q: What is the problem asking for?
- A: The problem asks to determine which artist received the most votes based on a dictionary mapping attendees' IDs to their voted artist.
-
Q: What are the inputs?
- A: A dictionary
votes
where keys are attendee IDs and values are the artists they voted for.
- A: A dictionary
-
Q: What are the outputs?
- A: The artist with the highest number of votes. In case of a tie, return any one of the top-voted artists.
P-lan
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Use a dictionary to count the votes for each artist and then determine the artist with the highest vote count.
1. Initialize an empty dictionary `vote_count` to count the votes for each artist.
2. Iterate through the `votes` dictionary.
- For each artist, increment their count in the `vote_count` dictionary.
3. Initialize variables `max_votes` to 0 and `winner` to an empty string.
4. Iterate through the `vote_count` dictionary to find the artist with the highest vote count.
- Update `max_votes` and `winner` whenever a higher vote count is found.
5. Return the `winner`.
I-mplement
def best_set(votes):
# Step 1: Initialize a frequency dictionary
vote_count = {}
# Step 2: Count the votes for each artist
for attendee, artist in votes.items():
if artist in vote_count:
vote_count[artist] += 1
else:
vote_count[artist] = 1
# Step 3: Find the artist with the highest vote count
max_votes = 0
winner = "
for artist, count in vote_count.items():
if count > max_votes:
max_votes = count
winner = artist
return winner