如何形成一个独特的收藏与一个元素从每个阵列拍摄?阵列、元素、独特、收藏

2023-09-11 23:22:50 作者:人丑任性

说我有3整型数组: {1,2,3},{2,3},{1}

我必须采取恰好一个要素从每个阵列,以形成一个新的数组,其中所有数字都是唯一的。在这个例子中,正确的答案是: {2,3,1}和{3,2,1} 。 (因为我必须采取一个元素从3数组,我希望所有的号码是唯一的,我绝不拿1号从第一个阵列。)

I must take exactly one element from each array, to form a new array where all numbers are unique. In this example, the correct answers are: {2,3,1} and {3,2,1}. (Since I must take one element from the 3rd array, and I want all numbers to be unique, I must never take the number 1 from the first array.)

我做了什么:

for a in array1:
    for b in array2:
        for c in array3:
            if a != b and a != c and b != c:
                AddAnswer(a,b,c)

这是蛮力,它的工作原理,但它并没有很好地扩展。如果现在我们正在处理的20阵列,而不是仅仅3。我不认为这是很好的写了20嵌套的for循环。有一个聪明的办法做到这一点?

This is brute force, which works, but it doesn't scale well. What if now we are dealing with 20 arrays instead of just 3. I don't think it's good to write a 20 nested for-loops. Is there a clever way to do this?

推荐答案

什么:

import itertools

arrs = [[1,2,3], [2,3], [1]]

for x in itertools.product(*arrs):
    if len(set(x)) < len(arrs): continue
    AddAnswer(x)

AddAnswer(X)被调用了两次,与元组:

AddAnswer(x) is called twice, with the tuples:


(2, 3, 1)
(3, 2, 1)