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 positioni, first leaves out the element and then includes it (and undoes it withpop()when coming back). Wheniequals 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.
1 2 3
{}
{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