Filter Destinations - codepath/compsci_guides GitHub Wiki

U-nderstand

Understand what the interviewer is asking for by using test cases and questions about the problem.

  • Q
    • What is the desired outcome?
      • To remove destinations from the dictionary that have a rating below the given threshold.
    • What input is provided?
      • A dictionary destinations mapping destination names to their rating scores, and an integer rating_threshold.

P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea: Iterate through the dictionary, identify the destinations with ratings below the threshold, and remove them.

1) Initialize a list `keys_to_remove` to store the keys of destinations to be removed.
2) Iterate through the dictionary:
   - If a destination's rating is below the threshold, add its key to `keys_to_remove`.
3) Remove the keys stored in `keys_to_remove` from the dictionary.
4) Return the updated dictionary.

⚠️ Common Mistakes

  • Modifying the dictionary while iterating over it.

I-mplement

def remove_low_rated_destinations(destinations, rating_threshold):
    keys_to_remove = []
    for dest, rating in destinations.items():
        if rating < rating_threshold:
            keys_to_remove.append(dest)
    
    for key in keys_to_remove:
        del destinations[key]
    
    return destinations