Skip to content

Squared

LeWiz24 edited this page Aug 27, 2024 · 3 revisions

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

Problem Highlights

  • 💡 Difficulty: Easy
  • Time to complete: 5 mins
  • 🛠️ Topics: List Manipulation, For 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 return if the input list numbers is empty?

    • A: The function should return an empty list [].
  • Q: How does the function handle each number in the list?

    • A: The function squares each number and stores the result in a new list.
  • The function squared() should take a list of integers and return a new list where each integer is squared.

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

EDGE CASE
Input: []
Output: []

P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea: Define the function to iterate through the list and square each integer.

1. Define the function `squared(numbers)`.
2. Initialize an empty list `squared_numbers` to store the squared values.
3. Iterate through each number in `numbers`:
    a. Square the number and append it to `squared_numbers`.
4. Return `squared_numbers`

⚠️ Common Mistakes

  • Forgetting to return the new list after processing.

I-mplement

Implement the code to solve the algorithm.

def squared(numbers):
    # Initialize an empty list to store the squared values
    squared_numbers = []
    
    # Iterate through each number in the input list
    for number in numbers:
        # Square the number and add it to the squared_numbers list
        squared_numbers.append(number ** 2)
    
    # Return the list of squared numbers
    return squared_numbers
Clone this wiki locally