rwjones
rwjones

Reputation: 377

Developing a recursive function in Python

I know I can do this with itertools, but I'm actually trying to learn how to start working with recursions.

I want to take the two values in this list...

[0, 1]

...and create a list of lists that contain it's permutations:

[ [0, 0], [0, 1], [1, 0], [1, 1] ]

I can do it with a comprehension and loops:

[ [i, j] for i in range(0, 2) for j in range(0, 2) ]

But that doesn't really scale well.

So if someone could help me understand how to do this with a recursive function that would scale to an arbitrary number of values in the original list I would appreciate it.

Upvotes: 2

Views: 184

Answers (1)

elnabo
elnabo

Reputation: 264

def cartesian_product(base, n=0):
        if (n ==  len(base)-1):
                return [[i] for i in base]
        res = []
        for i in base:
                for element in cartesian_product(base, n+1):
                        res.append([i]+element)
        return res

*Input: * cartesian_product([1,2])

*Output: * [[1, 1], [1, 2], [2, 1], [2, 2]]

Not the best way to do, but it's recursive. Each element is composed of one of the base element (1 or 2 in the exemple) + one element of the previous size (so [1] or [2]).

Upvotes: 4

Related Questions