Pankaj
Pankaj

Reputation: 517

Split a list into all pairs in all possible ways

I am aware of many posts with the similar questions and have been through all of them. However, I am not able to do what I need.

I have list say l1=[0,1,2,3,4] which I want to partition into pair of tuples like following:

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

I tried a solution from the post how-to-split-a-list-into-pairs-in-all-possible-ways.

def all_pairs(lst):
    if len(lst) < 2:
        yield lst
        return
    a = lst[0]
    for i in range(1,len(lst)):
        pair = (a,lst[i])
        for rest in all_pairs(lst[1:i]+lst[i+1:]):
            yield [pair] + rest

I get the following output:

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

I find that there are some combinations which are missing from the list which I want.

I would appreciate any suggestion?

Upvotes: 1

Views: 262

Answers (3)

cs95
cs95

Reputation: 402563

You can use itertools.permutations and filter out duplicates using frozenset:

In [173]: d = {frozenset([frozenset(x[:2]), frozenset(x[2:4]), x[-1]]) for x in itertools.permutations(l1, 
     ...: len(l1))}

In [174]: d2 = [sorted(x,  key=lambda x: (not isinstance(x, frozenset), x)) for x in d]

In [175]: sorted([[tuple(x[0]), tuple(x[1]), x[-1]] for x in d2])
Out[175]: 
[[(0, 4), (2, 3), 1],
 [(1, 2), (0, 3), 4],
 [(1, 2), (0, 4), 3],
 [(1, 2), (3, 4), 0],
 [(1, 3), (0, 2), 4],
 [(1, 3), (0, 4), 2],
 [(1, 3), (2, 4), 0],
 [(1, 4), (0, 2), 3],
 [(1, 4), (0, 3), 2],
 [(2, 3), (0, 1), 4],
 [(2, 3), (1, 4), 0],
 [(2, 4), (0, 1), 3],
 [(2, 4), (0, 3), 1],
 [(3, 4), (0, 1), 2],
 [(3, 4), (0, 2), 1]]

Upvotes: 3

stamaimer
stamaimer

Reputation: 6475

[[(0, i), tuple(item for item in l if item not in {0, i ,j}), j] for i in range(1, 5) for j in [item for item in l if item not in {0, i}]]

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

Upvotes: 1

Cory Madden
Cory Madden

Reputation: 5193

You could use itertools.permutations and then use a list comprehension to create pairs out of the first 4 items in each permuation:

l1=[0,1,2,3,4]
from itertools import permutations
l2 = permutations(l1)
l3 = [[(x[0], x[1]), (x[2], x[3]), x[4]] for x in l2]

Upvotes: 1

Related Questions