Reputation: 103
Like the title says, how can I find all of the ways a list can be divided into three lists? For example 1,2,3 would return
[1, 2, 3]
[1] [2] [3]
[1, 2] [3] [ ]
[1] [2, 3] [ ]
[1, 3] [2] [ ]
I've tried a bunch of stuff but just can't seem to get it. Thanks!
Upvotes: 1
Views: 83
Reputation: 127
you could use combinations
from the lib itertools
import itertools
my_list = [1, 2, 3]
for i in range(len(my_list)):
print(list(itertools.combinations(my_list, i + 1)))
which outputs
[(1,), (2,), (3,)]
[(1, 2), (1, 3), (2, 3)]
[(1, 2, 3)]
now you can add the length of each list and add the missing empty lists (to complete having 3 lists) and voila - you have your result
Upvotes: 2
Reputation: 56
Here is a possible solution:
import itertools
# your input data list
a = [1, 2, 3]
# util function to convert list of tuples to list of list
f = lambda x: [list(i) if isinstance(i, tuple) else i for i in x]
# list1 is all combinations of sublists having length = 1,2,..length_of_a from input list `a` and empty list []
list1 = []
for i in range(1, len(a)+1):
list1.extend(itertools.combinations(a, i))
list1.extend([()]*(len(a)-1))
# list2 is all combinations of sublists having length = length_of_a from the list1
list2 = list(set(itertools.combinations(list1, len(a))))
# filtering out and converting list of tuples for the final results
results = [f(i) for i in list2 if sum(itertools.chain(*i)) == sum(a) and set(itertools.chain(*i)) == set(a)]
results.append(a)
# print out the results
for r in results:
print(r)
Outputs:
[[1, 2, 3], [], []]
[[3], [1, 2], []]
[[1], [2], [3]]
[[2], [1, 3], []]
[[1], [2, 3], []]
[1, 2, 3]
Upvotes: 0