Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python how do I create variable length combinations or permutations?

Lets say I have an array called arr = [1,2,3,4]

How can I generate all the possible combinations with minimum 2 arguments that end up looking like

[1,2]
[1,3]
[1,4]
[1,2,3]
[1,2,4]
[1,2,3, 4]
[2,3]
[2,4]

and so on and so forth? Nothing Im trying works. I cant seem to use itertools.combinations or permutations because I need to know the argument size and I cant seem to use itertools.products because that will take minimum one argument from each of a list of lists that looks like this [[1],[2],[3],[4],[5]]. Extra thanks for one liners and comprehensions.

If I wanted to add them all together would that be too much to ask in terms of help? ;-)

like image 866
Leon Avatar asked Jul 16 '13 20:07

Leon


People also ask

How do you calculate permutations and combinations in Python?

To calculate the combinations of a dictionary in Python, use the itertools. combinations() method. The combinations() method takes a dictionary as an argument and returns all the possible combinations of the dictionary elements.

How do you write permutations in Python?

The number of permutations on a set of n elements is given by n!. For example, there are 2! = 2*1 = 2 permutations of {1, 2}, namely {1, 2} and {2, 1}, and 3! = 3*2*1 = 6 permutations of {1, 2, 3}, namely {1, 2, 3}, {1, 3, 2}, {2, 1, 3}, {2, 3, 1}, {3, 1, 2} and {3, 2, 1}.

How do you implement a combination in Python?

To create combinations without using itertools, iterate the list one by one and fix the first element of the list and make combinations with the remaining list. Similarly, iterate with all the list elements one by one by recursion of the remaining list.


1 Answers

How about:

(x for l in range(2, len(arr)) for x in itertools.combinations(arr, l))

or

[x for l in range(2, len(arr)) for x in itertools.combinations(arr, l)]

if you need the list.

This is the equivalent of the following nested loop

res = []
for l in range(2, len(arr)):
    for x in itertools.combinations(arr, l):
        res.append(x)
return res
like image 110
hivert Avatar answered Sep 22 '22 05:09

hivert