Last - codepath/compsci_guides GitHub Wiki
TIP102 Unit 1 Session 1 Standard (Click for link to problem statements)
Problem Highlights
- 💡 Difficulty: Easy
- ⏰ Time to complete: 5 mins
- 🛠️ Topics: Return Statements
U-nderstand
Understand what the interviewer is asking for by using test cases and questions about the problem.
-
Q: What should the function return if the list is empty?
- A: The function should return
None
.
- A: The function should return
-
Q: How does the function determine the last item in the list?
- A: The function uses negative indexing to access the last item in the list.
-
The function
get_last()
should accept a list of items and return the last item in the list. If the list is empty, it should return None.
HAPPY CASE
Input: ["spider man", "batman", "superman", "iron man", "wonder woman", "black adam"]
Output: "black adam"
EDGE CASE
Input: []
Output: None
P-lan
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Define the function to check if the list is empty and return the last item if it's not.
1. Define the function `get_last(items)`.
2. Check if `items` is not empty:
a. If not empty, return the last item using negative indexing (`items[-1]`).
b. If empty, return `None`.
⚠️ Common Mistakes
- Forgetting to handle the case when the list is empty.
I-mplement
Implement the code to solve the algorithm.
def get_last(items):
if items: # Check if the list is not empty
return items[-1] # Return the last item using negative indexing
else:
return None # Return None if the list is empty