Most Endangered Species - 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?
- A: To find the species with the lowest population from a list of species.
- Q: What input is provided?
- A: A list of dictionaries
species_list
, where each dictionary contains thename
,habitat
, andpopulation
of a species.
- A: A list of dictionaries
Input: species_list =
[
{"name": "Amur Leopard",
"habitat": "Temperate forests",
"population": 84
},
{"name": "Javan Rhino",
"habitat": "Tropical forests",
"population": 72
},
{"name": "Vaquita",
"habitat": "Marine",
"population": 10
}
]
Expected Output: Vaquita
P-lan
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Iterate through the list of species and keep track of the species with the lowest population.
1) Initialize the most endangered species as the first species in `species_list`.
2) Iterate through the list starting from the second element.
3) If the current species has a lower population than the current most endangered species, update the most endangered species.
4) Return the name of the most endangered species.
⚠️ Common Mistakes
- Not properly handling ties by returning the species with the lowest index.
I-mplement
def most_endangered(species_list):
# Initialize the most endangered species as the first species in the list
most_endangered_species = species_list[0]
# Iterate through each species in the list starting from the second element
for species in species_list[1:]:
# If the current species has a lower population, update the most endangered species
if species["population"] < most_endangered_species["population"]:
most_endangered_species = species
# Return the name of the species with the lowest population
return most_endangered_species["name"]