python codekatas solutions | Cell 8 | Cell 10 | Search

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.

Cell 9

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!')

What the code could have been:

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!')

Function Breakdown

Function Name: subsets

Purpose:

The subsets function generates all possible subsets of a given list.

Parameters:

Return Value:

A list containing all possible subsets of the input list.

Function Logic:

  1. If the input list s is empty, return a list containing an empty list ([[]]).
  2. Initialize an empty list res to store the subsets.
  3. Recursively call subsets on the input list s with the first element removed (s[1:]).
  4. For each subset generated in the recursive call, append a copy of the subset to res, and append a new subset that includes the first element of the original list (s[0]) followed by the subset.
  5. Return the res list containing all subsets.

Examples: