Understand what the interviewer is asking for by using test cases and questions about the problem.
species_list
, where each dictionary contains the name
, habitat
, and population
of a species.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
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
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"]