undefinedfix
Sign in

Pairing in arrays

xtu edited in Thu, 24 Nov 2022

There is an array. If you want to find all pairing cases, how to write it in Python is more elegant. For example, the input array is [1,2,3,4]

  • Case 11 was paired with case 2, and case 3 was paired with case 4
  • Cases 21 and 3 were paired, and cases 2 and 4 were paired
  • Cases 31 and 4 were paired, and cases 2 and 3 were paired

If we calculate all the three cases, there is no sequence of pairing


  • input
a=[1,2,3,4]
  • output
[  
    [[1, 2], [3, 4]],  
    [[1, 3], [2, 4]],  
    [[1, 4], [2, 3]]
]
4 Replies
purplemouse
commented on Fri, 25 Nov 2022
from itertools import combinations
print(list(combinations([1,2,3,4],2)))        #->[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]

  • sourceIteration of permutation and combination in Python cookbook 4.9"Python 3.6.5 standard library document" 10.1 itertools - functions for creating iterators for efficient loops
iyomb
commented on Fri, 25 Nov 2022

This is a DFS

ans = []
lst = [1,2,3,4]

def dfs(lst, tmp):
    if 2 == len(tmp):
        ans.append(tmp)
        return
    for i in range(len(lst)):
        dfs(lst[i+1:], tmp + [lst[i]])
dfs(lst, [])
hxyfm
commented on Fri, 25 Nov 2022

I don't know how to be more elegant. After a try, it can be like this:

def dfs(ls, r=2):
    c = []
    rs = []
    for x in itertools.combinations(ls, r):
        c.append(list(x))
    for i, j in itertools.combinations(c, r=2):
        x_set = set()
        x_set.update(i)
        x_set.update(j)
        x_rs = []
        if len(ls) == len(x_set):
            x_rs.append(i)
            x_rs.append(j)
            rs.append(x_rs)
    return rs


print("[1, 2, 3, 4]的结果=>", dfs(ls=[1, 2, 3, 4], r=2))
print("[1, 2, 3, 4, 5, 6]的结果=>", dfs(ls=[1, 2, 3, 4, 5, 6], r=3))

result:

[1, 2, 3, 4]的结果=> [[[1, 2], [3, 4]], [[1, 3], [2, 4]], [[1, 4], [2, 3]]]
[1, 2, 3, 4, 5, 6]的结果=> [[[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]]]
silvesthu
commented on Fri, 25 Nov 2022

After thinking about it for a long time, I don't know how to remove the for statement, which is not elegant.

a = [1, 2, 3, 4]  
b = []  
  
for i in range(1, len(a)):  
    b += zip(a[:-i], a[i:])  
  
b = [list(item) for item in b]  
  
print(b)

I don't know if the results meet the requirements.

[[1, 2], [2, 3], [3, 4], [1, 3], [2, 4], [1, 4]]