Kata Recursive Replication – Python Solution Video

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!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And 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?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become 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.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!