1

[1,2,3] I have this list and want to print all subsets of this list using recursion. I am getting the output using the following code but is there any better/easier way? Without typecasting it to a set.

def recur_subset(arr):
    if len(arr)==0:
        print(arr)
    else:
        for i in range(0, len(arr)):
            print(arr[0:i+1])
        for j in range(2, len(arr)):
            print([arr[0], arr[j]])

        return recur_subset(arr[1:len(arr)])
sidvish01
  • 11
  • 2
  • I recently wrote a [recursive `powerset` function](https://stackoverflow.com/a/53782303/6779307) as part of another answer. Is that what you're looking for? – Patrick Haugh Dec 16 '18 at 16:14

1 Answers1

0

You could use itertools to do the heavy lifting:

import itertools

def recur_subset( s, l=None ):
    if l == None:
        l = len(s)
    if l > 0:
        for x in itertools.combinations( s, l ):
            print(list(x))
        recur_subset( s, l-1 )

Note: This only prints non-empty subsets; add else: print([]) at the end to include the empty subset.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101