The subsets
function generates all possible subsets of a given list by recursively building upon itself, removing and adding elements to create new subsets. It returns a list containing all possible subsets of the input list, including the empty set and the original list itself.
def subsets(s):
"""Find all possible subsets of a list."""
if not s:
return [[]]
res = []
for sub in subsets(s[1:]):
res.append(sub)
res.append([s[0]]+sub)
return res
assert subsets('') == [[]]
# please note, inputs 'abc' and ['a', 'b', 'c'] should be equivalent for your function
assert subsets('abc') == [[],['a'],['b'],['a','b'],['c'],['a','c'],['b','c'],['a','b','c']]
assert subsets(['a','b','c']) == [[],['a'],['b'],['a','b'],['c'],['a','c'],['b','c'],['a','b','c']]
print('All passed!')
def subsets(input_list):
"""
Find all possible subsets of a list.
Args:
input_list (list): The input list to generate subsets from.
Returns:
list: A list of all possible subsets of the input list.
"""
if not input_list:
return [[]]
# Base case: if the list is empty, return a list containing an empty list
return _subsets_recursive(input_list)
def _subsets_recursive(input_list):
"""
Recursive helper function to generate subsets.
Args:
input_list (list): The input list to generate subsets from.
Returns:
list: A list of all possible subsets of the input list.
"""
# Base case: if the list is empty, return a list containing an empty list
if not input_list:
return [[]]
# Recursive case: get subsets of the list without the first element
subsets_without_first = _subsets_recursive(input_list[1:])
# Generate subsets with and without the first element
return subsets_without_first + [[input_list[0]] + sub for sub in subsets_without_first]
assert subsets('') == [[]]
assert subsets('abc') == [[], ['a'], ['b'], ['a', 'b'], ['c'], ['a', 'c'], ['b', 'c'], ['a', 'b', 'c']]
assert subsets(['a', 'b', 'c']) == [[], ['a'], ['b'], ['a', 'b'], ['c'], ['a', 'c'], ['b', 'c'], ['a', 'b', 'c']]
print('All passed!')
subsets
The subsets
function generates all possible subsets of a given list.
s
: The input list for which subsets are to be generated.A list containing all possible subsets of the input list.
s
is empty, return a list containing an empty list ([[]]
).res
to store the subsets.subsets
on the input list s
with the first element removed (s[1:]
).res
, and append a new subset that includes the first element of the original list (s[0]
) followed by the subset.res
list containing all subsets.subsets('')
returns [[]]
subsets('abc')
returns [[], ['a'], ['b'], ['a', 'b'], ['c'], ['a', 'c'], ['b', 'c'], ['a', 'b', 'c']]
subsets(['a', 'b', 'c'])
returns [[], ['a'], ['b'], ['a', 'b'], ['c'], ['a', 'c'], ['b', 'c'], ['a', 'b', 'c']]