如何形成一个独特的收藏与一个元素从每个阵列拍摄? [英] How to form an unique collection with one element taken from each array?

查看:116
本文介绍了如何形成一个独特的收藏与一个元素从每个阵列拍摄?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有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)

这篇关于如何形成一个独特的收藏与一个元素从每个阵列拍摄?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆