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? ;-)
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.
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}.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With