Skip to content

Instantly share code, notes, and snippets.

@chrisnatali
Created June 23, 2015 22:16
recursive all subsets
def all_subsets_rec(left, so_far, accum):
if len(left) == 0:
accum.append(so_far)
else:
# find subsets that include first item of left
all_subsets_rec(left[1:], [left[0]] + so_far, accum)
# find subsets that do NOT include first item of left
all_subsets_rec(left[1:], so_far, accum)
def all_subsets(items):
accum = []
all_subsets_rec(items, [], accum)
return accum
@vr2262
Copy link

vr2262 commented Jun 24, 2015

Check out the powerset recipe from the standard library: https://docs.python.org/3/library/itertools.html#itertools-recipes

To match the order your function produces, you can call reversed on range.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment