Is there a simple algorithm (most likely recursive algorithm) that finds all combinations of a list and of all sizes (from combo of size 1 to combo of size length of a list)?
For example: if I have a list = [1, 2, 3, 4], the combinations of all sizes I should get are:
[1], [2], [3], [4], [1,2], [1,3], [1,4], [2,3], [2,4], [3,4], [1,2,3], [1,2,4], [1,3,4], [2,3,4], [1,2,3,4].
So I only know a recursive algorithm I found online that finds a combination of size n but not for all sizes from 1 to length of the list. Order doesn't matter in combinations.
Here is the code I found online:
def n_length_combo(lst, n):
if n == 0:
return [[]]
l =[]
for i in range(0, len(lst)):
m = lst[i]
remLst = lst[i + 1:]
for p in n_length_combo(remLst, n-1):
l.append([m]+p)
return l
This is good only for combinations of size n. But I want to find combinations for all sizes from 1 to the length of a list.
Any ideas here?
itertools
module? – Samwise