Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting all possible combinations of a list in a form of sublists

I wonder if someone can help with the following task: What is the way to get all combinations a list can be split into sublists, when order does not matter?

Let's say I have a list of 4 items:

import itertools as it

a = [1, 2, 3, 4]
print(list(it.combinations(a, 2)))

That will give me a list of 6 possible pairs:

[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]

How to make (out of it? or any other way) a set of lists that contain original [1, 2, 3, 4] sequence in any order? So for this example it will contain three sublists:

 [(1, 2), (3, 4)]
 [(1, 3), (2, 4)]
 [(1, 4), (2, 3)]

UPDATE: A small clarification: In other words, I need to get all sets of n-tuples such that their members contain all the population of original list, when the order within an n-tuple does not matter. Thus [(1, 2), (3, 4)] is ok, but [(2, 1), (3, 4)] is not needed because it is the same as the first set, if we ignore the order.

UPDATE2: So for the list of length 6, and for chunks of size 2 this fun function should work as follows:

import itertools as it
a = [1, 2, 3, 4, 5, 6,]
r = 2

# fun(a,r):
# OUT:
# [
#    (1, 2), (3, 4), (5, 6)
#    (1, 3), (2, 4), (5, 6),
#    (1, 4), (2, 3), (5, 6),
#    (1, 5), (2, 3), (4, 6),
#    (1, 6), (2, 3), (4, 5),
#  ]
like image 920
David Pekker Avatar asked Aug 19 '18 08:08

David Pekker


People also ask

How do you generate all possible combinations of one list?

Enter the formula =List1. Expand out the new List1 column and then Close & Load the query to a table. The table will have all the combinations of items from both lists and we saved on making a custom column in List1 and avoided using a merge query altogether!

How many combinations of 4 numbers are there?

There are 10,000 possible combinations that the digits 0-9 can be arranged into to form a four-digit code.

How do you get all possible combinations of a list in python without Itertools?

To create combinations without using itertools, iterate the list one by one and fix the first element of the list and make combinations with the remaining list. Similarly, iterate with all the list elements one by one by recursion of the remaining list.


1 Answers

Just zip the combinations, with its reverse and take only the first half of the resulting list

>>> import itertools as it
>>> lst = [1, 2, 3, 4]
>>> r = len(lst)//2
>>> combs = list(it.combinations(lst, r))
>>> list(it.islice(zip(combs, reversed(combs)), len(combs)//2))
[((1, 2), (3, 4)), ((1, 3), (2, 4)), ((1, 4), (2, 3))]
like image 62
Sunitha Avatar answered Oct 22 '22 11:10

Sunitha