-2

Please I want to design a function that return all possible subset of a list. Here is the code I tried

def mylist(list1):
    for I in list1:
        print(i)
Ma0
  • 15,057
  • 4
  • 35
  • 65
  • 2
    can you please update your question to include an example input with the corresponding desired output? – Ma0 Feb 14 '18 at 17:00
  • without an example output, try this: https://stackoverflow.com/questions/26332412/python-recursive-function-to-display-all-subsets-of-given-set – Stev Feb 14 '18 at 17:02
  • You basically want the power set...check here using itertools library: https://stackoverflow.com/questions/18035595/powersets-in-python-using-itertools – rmilletich Feb 14 '18 at 17:09
  • Possible duplicate of [How can I find all the subsets of a set, with exactly n elements?](https://stackoverflow.com/questions/374626/how-can-i-find-all-the-subsets-of-a-set-with-exactly-n-elements) – ZaxR Feb 14 '18 at 19:29

2 Answers2

0

If what you're looking for is the powerset, itertools' recipe page has a nice, concise, memory-safe way to do that:

from itertools import chain, combinations

def powerset(iterable):
    """
    powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)
    """
    s = list(iterable)

    # note that this returns an iterator rather than a list
    return chain.from_iterable(combinations(s,n) for n in range(len(s)+1))

Worth pointing out that finding a powerset is exponential O(2^n). Also, this question had been previously answered here.

ZaxR
  • 4,896
  • 4
  • 23
  • 42
0

Just using iterative method for doing this as i looped from 0 to 2^(length of list) and select each element based on the value of the loop counter

That is if the loop counter is 5 we select the first and third element

as 5 in binary is represented as 101 the we select the index elements with 1 in binary likewise for 7 we need first three elements 111

def mylist(list1):
    num=len(list1)
    result=[]
    for i in range(1<<num):
        temp=list()
        index=0
        while i:
            if i&1==1:
                temp.append(list1[index])
            index+=1;
            i>>=1
        result.append(temp)
    return result

print(mylist([1,2,3]))

OUTPUT

[[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]

also you might want convert this function to a generator as the returned list will be huge if the inputlist contains large number of values

Albin Paul
  • 3,330
  • 2
  • 14
  • 30