Codepath

Split Haycorns

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

Problem Highlights

  • 💡 Difficulty: Easy
  • Time to complete: 5 mins
  • 🛠️ Topics: Divisors, Loops

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 quantity is 1?
    • A: The function should return [1] since 1 can only be divided by itself.
  • Q: Should the function include both 1 and quantity as divisors?

    • A: Yes, both 1 and quantity should be included as they are valid divisors.
  • The function split_haycorns() should take a positive integer quantity and return a list of all divisors of quantity.

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

EDGE CASE
Input: 1
Expected Output: [1]

P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea: Define a function that iterates through numbers from 1 to quantity and checks if they are divisors of quantity.

1. Define the function `split_haycorns(quantity)`.
2. Initialize an empty list `divisors` to store the divisors.
3. Iterate through all numbers from 1 to `quantity` (inclusive).
4. For each number, check if it is a divisor of `quantity` using the modulo operator (`quantity % i == 0`).
5. If it is a divisor, add it to the `divisors` list.
6. Return the `divisors` list.

⚠️ Common Mistakes

  • Not handling the case where quantity is 1, which should correctly return [1].

I-mplement

Implement the code to solve the algorithm.

def split_haycorns(quantity):
    # Initialize an empty list to store the divisors
    divisors = []
    
    # Iterate through all numbers from 1 to quantity (inclusive)
    for i in range(1, quantity + 1):
        # If i is a divisor of quantity, add it to the list
        if quantity % i == 0:
            divisors.append(i)
    
    # Return the list of divisors
    return divisors
Fork me on GitHub