87. All subsets
A subset of a list is any selection of its items, from none of them to all of them. [1, 2, 3] has 8 subsets:
[], [1], [2], [3], [1, 2], [1, 3], [2, 3] and [1, 2, 3]. Each item is either in or out, so n items
have 2^n subsets.
Write a function subsets(items) that takes a list of different whole numbers, sorted from smallest to largest, and
returns all of its subsets:
- Each subset is a list with its numbers in increasing order.
- The empty subset
[]and the whole list are both included. - The subsets are sorted by size, smallest first, and subsets of the same size in dictionary order:
[1, 2]before[1, 3]before[2, 3].
Write the search yourself, without itertools: it is the pattern behind many backtracking problems.
Example 1
items = [1, 2, 3][[], [1], [2], [3], [1, 2], [1, 3], [2, 3],
[1, 2, 3]]Example 2
items = [5][[], [5]]Example 3
items = [][[]]Constraints
itemshas 0 to 8 different whole numbers, from -100 to 100, sorted from smallest to largest.
Submit also runs 4 more tests you can't see.
Practises Recursion (lesson 20).
- Decide the items one at a time. A helper
collect(items, i, chosen, found)makes both choices foritems[i]: once with it appended tochosen, once without, each followed by a call fori + 1. - When
i == len(items)every item has been decided: record a copy,chosen[:], sincechosenkeeps changing. Remove the item again (chosen.pop()) before trying the "without" branch. - The calls find the subsets in a different order. Sort them at the end with the key
lambda s: (len(s), s): size first, then the lists themselves.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
def subsets(items):
"""List every subset of items.
items: list of int, different, sorted; may be empty
Returns: list of lists, all 2^n subsets, by size and
then in dictionary order
"""
# Write your code here
pass
Run your code to see how it does on the test cases, or Submit to check every test.