Filter Scenes by Keyword - codepath/compsci_guides GitHub Wiki

Unit 4 Session 2 Advanced (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 goal of the problem?
    • A: The goal is to filter out scenes from a list that contain a specified keyword.
  • Q: What are the inputs?
    • A: The input is a list of scene descriptions (strings) and a keyword (string).
  • Q: What are the outputs?
    • A: The output is a list of scenes that do not contain the specified keyword.
  • Q: How should keyword matching be handled?
    • A: The function should check if the keyword is a substring of any scene description. If the keyword is found, that scene should be filtered out.
  • Q: Are there any assumptions about the input?
    • A: The scenes and keyword are non-empty strings, and the list of scenes may contain multiple entries.

P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea: Iterate through the list of scenes and check if each scene contains the keyword. If a scene does not contain the keyword, add it to the result list.

1) Initialize an empty list `filtered_scenes` to store scenes that do not contain the keyword.
2) Iterate through each scene in the `scenes` list:
   a) If the keyword is not found in the scene, add the scene to `filtered_scenes`.
3) Return the `filtered_scenes` list.

**⚠️ Common Mistakes**

- Forgetting to check for the keyword as a substring, which could lead to incorrect filtering.
- Not considering case sensitivity, although this is not required by the problem as stated.
- Assuming that every scene will contain the keyword, which might not be true.

I-mplement

def filter_scenes_by_keyword(scenes, keyword):
    filtered_scenes = []

    for scene in scenes:
        if keyword not in scene:
            filtered_scenes.append(scene)

    return filtered_scenes
Example Usage:

scenes = [
    "The hero enters the dark forest.",
    "A mysterious figure appears.",
    "The hero finds a hidden treasure.",
    "An eerie silence fills the air."
]
keyword = "hero"

filtered_scenes = filter_scenes_by_keyword(scenes, keyword)
print(filtered_scenes)  
# Output: ['A mysterious figure appears.', 'An eerie silence fills the air.']

scenes = [
    "The spaceship lands on an alien planet.",
    "A strange creature approaches the crew.",
    "The crew prepares to explore the new world."
]
keyword = "crew"

filtered_scenes = filter_scenes_by_keyword(scenes, keyword)
print(filtered_scenes)  
# Output: ['The spaceship lands on an alien planet.']