Prioritizing Endangered Species Observations - 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 sort observed_species such that species in priority_species appear first and in the order given, with other species sorted at the end.
    • What input is provided?
      • Two lists, observed_species and priority_species.

P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea: Count occurrences of each species in observed_species, prioritize those in priority_species, and sort the remaining species.

1) Count the occurrences of each species in `observed_species`.
2) Initialize a list `result` to store the sorted species.
3) Append species from `priority_species` to `result` in order, then remove them from the count.
4) Append and sort the remaining species to `result`.
5) Return `result`.

⚠️ Common Mistakes

  • Not correctly handling species not in priority_species.

I-mplement

def prioritize_observations(observed_species, priority_species):
    # Count the occurrences of each element in observed_species
    count = {}
    for species in observed_species:
        if species in count:
            count[species] += 1
        else:
            count[species] = 1

    # Result array
    result = []

    # Add elements of priority_species to result in the order of priority_species
    for species in priority_species:
        if species in count:
            result.extend([species] * count[species])
            del count[species]  # Remove the element from count after processing

    # Remaining elements in observed_species that are not in priority_species
    remaining = []
    for species in observed_species:
        if species in count:
            remaining.append(species)

    # Sort the remaining elements
    remaining.sort()

    # Append the sorted remaining elements to result
    result.extend(remaining)

    return result