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?