On this page
Student Directory
TIP101 Unit 2 Session 1 (Click for link to problem statements)
U-nderstand
Understand what the interviewer is asking for by using test cases and questions about the problem.
- What is the input?
- A list of student names,
student_names.
- A list of student names,
- What should the function return?
- A dictionary that maps each student name to an ID.
- How are IDs assigned?
- The first name gets ID 1, and each following name gets the next number, in list order.
- What if the list is empty?
- Return an empty dictionary.
HAPPY CASE
Input: student_names = ["Ada", "Grace", "Alan"]
Output: {"Ada": 1, "Grace": 2, "Alan": 3}
Explanation: IDs start at 1 and go up by one for each name in order.
EDGE CASE
Input: student_names = []
Output: {}
Explanation: There are no students, so the directory is empty.
P-lan
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Create a dictionary from a list of keys (student names) and generate a unique ID for each value.
1) Create a new, empty dict
2) The current student ID starts at 1
3) For each student name:
a) In the new dict, map name -> current ID
b) Increment current ID by one
4) Return the new dict
I-mplement
def student_directory(student_names):
student_dict = {}
student_id = 1 # Start student IDs at 1
for name in student_names:
student_dict[name] = student_id
student_id += 1
return student_dict