I have a list of, say, 3 players:
[1, 2, 3]
How can I generate, in python, a list of lists, of the form:
[[1], [2], [3], [1,2], [1,3], [2,3], [1,2,3]]
representing all teams that can be formed with the above players?
I have a list of, say, 3 players:
[1, 2, 3]
How can I generate, in python, a list of lists, of the form:
[[1], [2], [3], [1,2], [1,3], [2,3], [1,2,3]]
representing all teams that can be formed with the above players?
You could use itertools.combinations()
where we can set r
parameter to all lengths from 1 to length of our list (x
), to get all possible combinations that are going to be flattened in list comprehension.
from itertools import combinations
x = [1, 2, 3]
result = [c for i in range(1, len(x)+1) for c in combinations(x, i)]
print(result) # -> [(1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]
Use https://docs.python.org/3/library/itertools.html#itertools.combinations
It does exactly what you want.
import itertools
players = [1, 2, 3]
print(list(itertools.chain.from_iterable(itertools.combinations(players, r) for r in range(1, len(players) + 1))))
Output:
[(1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]
This is probably the most efficient answer due to the use of itertools.chain
You can use itertools.combinations
with a given size to generate fixed size combinations. In order to generalize, you can just use a for loop over all the sizes. The code would look like this:
import itertools
my_list = [1, 2, 3]
for L in range(0, len(my_list)+1):
for subset in itertools.combinations(my_list, L):
print(subset)
You can use itertools
. What you want to do is generate powerset of the given list.
>>> import itertools
>>> a=[1,2,3]
>>> out=[]
>>> for i in range(len(a)+1):
out+=list(itertools.combinations(a,i))
>>> out
[(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]
>>>
You can write recursive
function to generate powerset as follows:
>>> def powerset(s,idx,curr,out):
if idx==len(s):
out.append(curr)
return
(powerset(s,idx+1,curr+[s[idx]],out))
(powerset(s,idx+1,curr,out))
return sorted(out,key=lambda x:len(x))
>>> z=powerset(a,0,[],[])
>>> z
[[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
Itertools is you friend for these kind of operations:
import itertools
l = [1, 2, 3]
l = [list(x) for y in range(1,len(l)+1) for x in itertools.combinations(l,y) ]
print(l)
Gives:
[[1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]