Codepath

Double Trouble

TIP102 Unit 1 Session 1 Standard (Click for link to problem statements)

Problem Highlights

  • 💡 Difficulty: Easy
  • Time to complete: 5 mins
  • 🛠️ Topics: List Iteration, Loops, 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 doubled() do?

    • A: The function should accept a list of integers hunny_jars and return a new list where each element is multiplied by two.
  • Q: Should the original list be modified?

    • A: No, the function should return a new list and not modify the original list.
  • Q: What happens if the list is empty?

    • A: The function should return an empty list.
  • The function doubled() should take a list of integers, hunny_jars, and return a new list where each element is multiplied by 2.

HAPPY CASE
Input: [1, 2, 3]
Expected Output: [2, 4, 6]

Input: [4, 5, 6]
Expected Output: [8, 10, 12]

EDGE CASE
Input: []
Expected Output: []

P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea: Define a function that iterates through the list, multiplies each element by 2, and stores the results in a new list which is then returned.

1. Define the function `doubled(hunny_jars)`.
2. Initialize an empty list `doubled_jars` to store the doubled values.
3. Iterate through each element in `hunny_jars`.
4. Multiply each element by 2 and append it to `doubled_jars`.
5. Return `doubled_jars`.

⚠️ Common Mistakes

  • Forgetting to initialize the result list.
  • Not correctly multiplying each element by 2.

I-mplement

Implement the code to solve the algorithm.

def doubled(hunny_jars):
    # Create a new list to store the doubled values
    doubled_jars = []
    
    # Loop through each element in the input list
    for jar in hunny_jars:
        # Multiply the element by 2 and add it to the new list
        doubled_jars.append(jar * 2)
    
    # Return the new list
    return doubled_jars
Fork me on GitHub