-
Notifications
You must be signed in to change notification settings - Fork 244
Name the Node
LeWiz24 edited this page Sep 9, 2024
·
4 revisions
Unit 2 Session 1 (Click for link to problem statements)
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 name suggestion received the most votes from a list of suggestions. If there is a tie, return any of the suggestions with the highest votes.
-
Q: What are the inputs?
- A: A list of strings
votes
where each string is a suggested name.
- A: A list of strings
-
Q: What are the outputs?
- A: A string representing the suggestion with the most votes. If there is a tie, return any of the top suggestions.
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Use a dictionary to count the votes for each suggestion and then determine the suggestion with the highest vote count.
1. Initialize an empty dictionary `vote_count` to count the votes for each suggestion.
2. Iterate through the `votes` list.
- For each vote, increment its 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 suggestion with the highest vote count.
- Update `max_votes` and `winner` whenever a higher vote count is found.
5. Return the `winner`.
def get_winner(votes):
# Step 1: Initialize a frequency dictionary
vote_count = {}
# Step 2: Count the votes
for vote in votes:
if vote in vote_count:
vote_count[vote] += 1
else:
vote_count[vote] = 1
# Step 3: Find the suggestion with the highest count
max_votes = 0
winner = ""
for suggestion, count in vote_count.items():
if count > max_votes:
max_votes = count
winner = suggestion
return winner