TIP102 Unit 1 Session 1 Standard (Click for link to problem statements)
Understand what the interviewer is asking for by using test cases and questions about the problem.
Q: What should be returned by the function?
The function running_sum()
should take a list of integers superhero_stats
and modify it in place to return the running sum. The modified list should reflect the cumulative sum such that superhero_stats[i] = sum(superhero_stats[0]...superhero_stats[i])
.
HAPPY CASE
Input: [1, 2, 3, 4]
Expected Output: [1, 3, 6, 10]
Input: [1, 1, 1, 1, 1]
Expected Output: [1, 2, 3, 4, 5]
EDGE CASE
Input: [3, 1, 2, 10, 1]
Expected Output: [3, 4, 6, 16, 17]
Input: [] (empty list)
Expected Output: []
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Iterate through the list starting from the second element and modify each element to include the sum of itself and the previous element.
1. Define the function `running_sum(superhero_stats)`.
2. If the list is empty, return immediately.
3. Iterate through the list starting from index 1.
4. Update the current element by adding the previous element to it.
⚠️ Common Mistakes
Implement the code to solve the algorithm.
def running_sum(superhero_stats):
# Iterate through the list starting from the second element
for i in range(1, len(superhero_stats)):
# Update the current element to be the sum of itself and the previous element
superhero_stats[i] += superhero_stats[i - 1]