Search and backtracking · 6 / 15 Exercise Medium

All subsets

Objective

Create a Python program that generates all the subsets of a list. It is the simplest example of exhaustive recursion: for each element there are two options, leave it out or include it.

Instructions

  • Read a line with distinct integers separated by spaces (at most 5).
  • Write a recursive function subsets(values, i, current, result) that, for position i, first leaves out the element and then includes it (and undoes it with pop() when coming back). When i equals the size of the list, store a copy of the current subset.
  • Show each subset on a line, in the order they are generated, with the format {1, 3} (the empty one is {}).
  • Finish with Total: t.
Input
1 2 3
Output
{}
{3}
{2}
{2, 3}
{1}
{1, 3}
{1, 2}
{1, 2, 3}
Total: 8

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise