- Notifications
You must be signed in to change notification settings - Fork 266
Total Honey
LeWiz24 edited this page Aug 26, 2024 · 4 revisions
TIP102 Unit 1 Session 1 Standard (Click for link to problem statements)
- 💡 Difficulty: Easy
- ⏰ Time to complete: 5 mins
- 🛠️ Topics: List Iterations, Loops
Understand what the interviewer is asking for by using test cases and questions about the problem.
-
Q: What should the function
sum_honey()
do?- A: The function should take a list of integers
hunny_jars
and return the sum of all elements in the list.
- A: The function should take a list of integers
-
Q: Can the built-in
sum()
function be used?- A: No, the problem explicitly states that the
sum()
function should not be used.
- A: No, the problem explicitly states that the
-
Q: What happens if the list is empty?
- A: The function should return
0
since there are no elements to add.
- A: The function should return
-
The function
sum_honey()
should take a list of integers,hunny_jars
, and return the sum of all the elements in the list without using the built-insum()
function.
HAPPY CASE Input: [2, 3, 4, 5] Expected Output: 14 Input: [10, 20, 30] Expected Output: 60 EDGE CASE Input: [] Expected Output: 0
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Define a function that initializes a sum variable to 0, iterates through the list, adds each element to the sum variable, and returns the sum.
1. Define the function `sum_honey(hunny_jars)`. 2. Initialize a variable `total_honey` to 0. 3. Iterate through each element in `hunny_jars`. 4. Add each element to `total_honey`. 5. Return `total_honey`
- Forgetting to initialize the sum variable.
- Not correctly iterating through the list.
Implement the code to solve the algorithm.
def sum_honey(hunny_jars): # Initialize the sum variable to 0 total_honey = 0 # Iterate through each element in the list for jar in hunny_jars: # Add the element to the total sum total_honey += jar # Return the total sum return total_honey