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
-
This may be helpful (the source code for the python itertools module) : github.com/python/cpython/blob/master/Modules/itertoolsmodule.cJacobIRR– JacobIRR05/11/2020 17:17:41Commented May 11, 2020 at 17:17
-
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])sonus21– sonus2105/11/2020 17:17:43Commented May 11, 2020 at 17:17
-
@JacobIRR my teacher doesn t want us to use itertools for some reasonDiogo Silva– Diogo Silva05/11/2020 17:21:01Commented May 11, 2020 at 17:21
-
@sonus21 I want to know why it doesn t work this way, I think it makes sense like thisDiogo Silva– Diogo Silva05/11/2020 17:21:51Commented May 11, 2020 at 17:21
-
@DiogoSilva The reason this won't work is because the larger the list, the more time it will take. This has exponential time.10 Rep– 10 Rep05/11/2020 17:24:01Commented May 11, 2020 at 17:24
3 Answers 3
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])
answered May 11, 2020 at 17:22
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))
answered May 11, 2020 at 17:20
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
lang-py