2

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.

8
  • In what way do you want it to scale? Commented Jul 24, 2013 at 12:16
  • 1
    If you're interested, you can see the code for itertools.product here: docs.python.org/2/library/itertools.html#itertools.product Commented Jul 24, 2013 at 12:18
  • @AntonisChristofides: if the original list contains significantly more than two elements, the 'for' loops will eventually become unmanageable. Commented Jul 24, 2013 at 12:32
  • @Haidro: Thanks. I hadn't thought of that. Commented Jul 24, 2013 at 12:34
  • Those are not permutations. Permutations of this list would be [0,1] and [1,0]. You mean sth like combinations of n elements, taken from a base set. Commented Jul 24, 2013 at 12:37

1 Answer 1

4
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]).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.