Home > Software engineering >  Why do I get an empty list after a recursive function?
Why do I get an empty list after a recursive function?

Time:01-01

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)

CodePudding user response:

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)))
  • Related