You should pass your result
list as well, like below. But I think this recursive function doesn't do that what you want to do.
def combination(l, result=[]):
for item in range(len(l)):
cut_list = l[:item] + l[item + 1:]
if len(cut_list) > 1:
combination(cut_list, result)
elif len(cut_list) == 1:
result += cut_list
return result
print(combination([3, 22, 10, 15, 32, 10, 5]))
Result:
>>> python3 test.py
[5, 10, 5, 32, 10, 32, 5, 10, 5, 15, 10, 15, 5, 32, 5, 15, 32, ...
You can get the all combinations/permutations without recursion:
Permutations:
import itertools
stuff = [1, 2, 3]
for L in range(0, len(stuff)+1):
for subset in itertools.permutations(stuff, L):
print(subset)
Output:
>>> python3 test.py
()
(1,)
(2,)
(3,)
(1, 2)
(1, 3)
(2, 1)
(2, 3)
(3, 1)
(3, 2)
(1, 2, 3)
(1, 3, 2)
(2, 1, 3)
(2, 3, 1)
(3, 1, 2)
(3, 2, 1)
Combinations (This mechanism matches with your description in your question):
import itertools
stuff = [1, 2, 3]
for L in range(0, len(stuff)+1):
for subset in itertools.combinations(stuff, L):
print(subset)
Output:
>>> python3 test.py
()
(1,)
(2,)
(3,)
(1, 2)
(1, 3)
(2, 3)
(1, 2, 3)
EDIT:
Of course, you can make a function from my below example and you can get the result as a nested list.
Code:
import itertools
def combination(l):
result = []
for L in range(0, len(l)+1):
for subset in itertools.combinations(l, L):
result.append(list(subset))
return result
print(combination([1, 2, 3]))
Output:
>>> python3 test.py
[[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
EDIT_2:
Solution without itertools
module:
Code:
def combinations(return_len, iterable):
if not return_len:
return [[]]
if not iterable:
return []
head = [iterable[0]]
tail = iterable[1:]
new_comb = [head + list_ for list_ in combinations(return_len - 1, tail)]
return new_comb + combinations(return_len, tail)
input_list = [1, 2, 3]
result = []
for n in range(0, len(input_list) + 1):
for single_result in combinations(n, input_list):
result.append(single_result)
print(result)
Output:
>>> python3 test.py
[[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]