Kata Recursive Replication – Python Solution Video

Rate this post

Problem Formulation

The following problem formulation is taken from this Kata.


Design a recursive function called replicate(times, number) that returns an array of repetitions of the number argument.

For example, replicate(3, 5) should return the list [5, 5, 5].

If the times argument is negative, return an empty array.

Do not use loops to solve this problem.

Background Resources

Video Solution

This video solution is contributed by Finxter Creator Clement:

Code Solution

Here’s the code discussed in tihs video:

def replicate(times, number):
    # the forbidden way
    result = []
    for i in range(times):
        result.append(number)
    return result


def replicate(times, number):
    # recursive solution
    if times <= 0:
        return [] # base case and exception handling
    return replicate(times-1, number) + [number]
    
    

The first function uses the for loop, the second function uses the recursive solution with the base case and the recursion case.

Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!