Diogo Silva
Diogo Silva

Reputation: 15

Permutations in python

I have a list of sets and I want to get a list of all sublists possible. This is what I ve written until now. For some reason it is not including the last position and I don't understand why.

def all_sublists(sets):
    l = []

    for i in range(0,len(sets)):
        for j in range(0,len(sets)):
            for step in range(1,len(sets)):
                if sets[i:j:step] not in l:
                    l.append(sets[i:j:step])     
    return l


def fun(sets):
    x = all_sublists(sets)

    for element in x:
        print(element)


    return 0

And this is my output: enter image description here

Upvotes: 0

Views: 131

Answers (3)

OnePro
OnePro

Reputation: 41

Add +1 in second loop. range(0,len(sets)+1)

def all_sublists(sets):
    l = []

    for i in range(0,len(sets)):
        for j in range(0,len(sets)+1):
            for step in range(1,len(sets)):
                if sets[i:j:step] not in l:
                    l.append(sets[i:j:step])     
    return l


def fun(sets):
    x = all_sublists(sets)

    for element in x:
        print(element)


    return 0

Upvotes: 0

Bobby Ocean
Bobby Ocean

Reputation: 3328

Use the itertools library.

import itertools as it

my_list      = [{1,2,3},{2,4},{3,4},{4,5}]
combinations = it.chain(*(it.combinations(my_list,i) for i in range(len(my_list))))

print(list(combinations))

EDIT:

Well, powersets are 2^N given a list of size N, hence your formula needs to account for the binary selection process. Something like

def powerset(sets):
    pset = []
    for i in range(2**len(sets)):
        subset = []
        for n,keep in enumerate(bin(i)[2:].zfill(len(sets))):
            if keep == '1':
                subset.append(sets[n])
        pset.append(subset)
    return pset

pset([1,2,3])




Upvotes: 1

Alex Hall
Alex Hall

Reputation: 36043

From https://docs.python.org/3/library/itertools.html#itertools-recipes:

def powerset(iterable):
    "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
    s = list(iterable)
    return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))

Upvotes: 0

Related Questions