logo CodeStepByStep logo

subsets

Language/Type: Python recursion recursive backtracking

Write a function subsets that uses recursive backtracking to find every possible sub-list of a given list. A sub-list of a list L contains 0 or more of L's elements. Your function should accept a list of strings as its parameter and print every sub-list that could be created from elements of that list, one per line. For example, suppose a variable called lst stores the following elements:

[Janet, Robert, Morgan, Char]

The call of subsets(lst) would produce output such as the following:

['Janet', 'Robert', 'Morgan', 'Char']
['Janet', 'Robert', 'Morgan']
['Janet', 'Robert', 'Char']
['Janet', 'Robert']
['Janet', 'Morgan', 'Char']
['Janet', 'Morgan']
['Janet', 'Char']
['Janet']
['Robert', 'Morgan', 'Char']
['Robert', 'Morgan']
['Robert', 'Char']
['Robert']
['Morgan', 'Char']
['Morgan']
['Char']
[]

The order in which you show the sub-lists does not matter, and the order of the elements of each sub-list also does not matter. The key thing is that your function should produce the correct overall set of sub-lists as its output. Notice that the empty list is considered one of these sub-lists. You may assume that the list passed contains no duplicates. Do not use any loops in solving this problem.

Function: Write a Python function as described, not a complete program.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.