While working on a recursive function to generate the set of all subsets, I noticed that this fuction defined below gave me an unexpected output of:
[[]], None, None, None and None.
Why does it "work" properly when the for-loop is active, whereas it completely does not map to the desired subsets when it is not active.
print(ss)
Does not print the same thing it does when the for-loop is active.
What am I missing?
def get_all_subsets(some_list):
"""Returns all subsets of size 0 - len(some_list) for some_list"""
if len(some_list) == 0:
# If the list is empty, return the empty list
return [[]]
subsets = []
first_elt = some_list[0]
rest_list = some_list[1:]
ss = get_all_subsets(rest_list)
print(ss)
# for partial_subset in ss:
# subsets.append(partial_subset)
# next_element = partial_subset[:] + [first_elt]
# subsets.append(next_element)
# return subsets
L = [1,2,3,4]
print(get_all_subsets(L))
What I want to see is:
[[2,3,4],[3,4],[4],[]]
Here is a more S-O worthy code:
def get_all_subsets(some_list):
"""Returns all subsets of size 0 - len(some_list) for some_list"""
if len(some_list) == 0:
# If the list is empty, return the empty list
return [[]]
subsets = []
first_elt = some_list[0]
rest_list = some_list[1:]
ss = get_all_subsets(rest_list)
print(ss)
for partial_subset in ss:
print(partial_subset)
# subsets.append(partial_subset)
# next_element = partial_subset[:] + [first_elt]
# subsets.append(next_element)
return subsets