Why do I get an empty list after a recursive function?

Question:

subset = []
subsets = []


def search(k, n):
    if k == n and subset:
        subsets.append(subset)
    else:
        search(k + 1, n)
        subset.append(k)
        search(k + 1, n)
        del subset[-1]


search(0, 5)

This is supposed to store all of the nonempty subsets of [1, 2, 3, 4, 5] in the list subsets.

I got that subsets is a list of empty lists, but I expected subsets to be a list of all nonempty subsets of [1, 2, 3, 4, 5]. I also tried to place the global keyword in before the function. Am I doing something wrong? (I know that in Java the problem was solved by adding the new keyword in front of the subset, so I would use subsets.add(new ArrayList<>(subset)). But in python, I don’t think this problem exists)

Asked By: py_math

||

Answers:

You do, in fact, need to make a copy of the subset list just like you would in Java for essentially the same reasons. (Otherwise, you’re just adding the same reference to the result multiple times and all updates are reflected in each of them.)

if k == n:
    if subset:
        subsets.append(list(subset))
else:
    search(k + 1, n)
    subset.append(k)
    search(k + 1, n)
    del subset[-1]

You can use itertools.combinations for a simpler solution.

import itertools
def non_empty_subsequences(l):
    return [list(s) for i in range(1, len(l) + 1) for s in itertools.combinations(l, i)]
print(non_empty_subsequences(range(1,6)))
Answered By: Unmitigated
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.