Creating dependent combinations from an array

I would like to generate combinations from an array (always 4 elements):

arr = ["1","2","3","4"]

I am currently using:

itertools.combinations(arr, 2)

This returns me the pairs:

 ("1","2"),("1","3"),("1","4"),("2","3"),("2","4"),("3","4")

What I would like to do is only create dependent combinations:

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

Meaning, if I have a combination of strings "1"and "2", the rest of the combination remains "3"and "4". In my current solution, it is used only itertools, and because of this, each calculation is performed twice (once for a pair of "1","2"s "3","4"(so the pair "3","4"in this case is calculated separately, iterating over arr, again coming out "1"and "2"), and at another time the "3","4"pair s "1","2").

I believe that there should be a more elegant way to solve this problem.

+4
2

4 ( ), :

arr = ["1","2","3","4"]
for i in range(1,4):
    print([arr[0], arr[i]], arr[1:i] + arr[i+1:])

#output: 
['1', '2'] ['3', '4']
['1', '3'] ['2', '4']
['1', '4'] ['2', '3']
+2

, , , :

from itertools import combinations

arr = [1, 2, 3, 4, 5, 6]
group_size = len(arr) // 2

tuples = list(combinations(arr, group_size))
dependent_combinations = [
  [tuples[i], tuples[-i-1]]
  for i in range(len(tuples) // 2)
]
print(dependent_combinations)

:

[
    [(1, 2, 3), (4, 5, 6)],
    [(1, 2, 4), (3, 5, 6)],
    [(1, 2, 5), (3, 4, 6)],
    [(1, 2, 6), (3, 4, 5)],
    [(1, 3, 4), (2, 5, 6)],
    [(1, 3, 5), (2, 4, 6)],
    [(1, 3, 6), (2, 4, 5)],
    [(1, 4, 5), (2, 3, 6)],
    [(1, 4, 6), (2, 3, 5)],
    [(1, 5, 6), (2, 3, 4)]
]
+3

Source: https://habr.com/ru/post/1676816/


All Articles