Python recursive function to display all subsets of given set Python recursive function to display all subsets of given set arrays arrays

Python recursive function to display all subsets of given set


def subs(l):    if l == []:        return [[]]    x = subs(l[1:])    return x + [[l[0]] + y for y in x]

Results:

>>> print (subs([1, 2, 3]))[[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]]


There is a convenient Python module to help:

import itertoolsdef subs(l):    res = []    for i in range(1, len(l) + 1):        for combo in itertools.combinations(l, i):            res.append(list(combo))    return res

The results are:

>>> subs([1,2,3])[[1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]


Actually there is no problem with Python call by reference as I originally thought. In that case l[-1] would be 8 in all recursive calls. But l[-1] is 3, 5, 8 respectively in the recursive calls. This modified function solves the issue:

def subs(l):    if len(l) == 1:        return [l]    res = []    subsets = subs(l[0:-1])    res = res+subsets    res.append([l[-1]])    for sub in subsets:        res.append(sub+[l[-1]])    return res

returns:

[[2], [3], [2, 3], [5], [2, 5], [3, 5], [2, 3, 5], [8], [2, 8], [3, 8], [2, 3, 8], [5, 8], [2, 5, 8], [3, 5, 8], [2, 3, 5, 8]]