简体   繁体   English

在Python的排列下没有元素相同的集合的笛卡尔积

[英]Cartesian Product of Sets where No Elements are Identical under Permutations in Python

I have some sets I would like to take the Cartesian product of, which is working well. 我有一些我想采用的笛卡尔积,效果很好。 However, I want to remove all elements of this new set which are identical under a permutation of the elements. 但是,我想删除此新集合中所有在元素置换后都相同的元素。

For example, take the following code: 例如,使用以下代码:

import itertools as ittools
x = 2
y = 3
z = 5

flist = list(ittools.product([x,y,z],repeat=3))

for f in flist:
    print reduce(lambda a,b: a*b, f)

This code find the Cartesian product of the set {2,3,5} and returns the product of all three components of each element in the resulting set. 该代码查找集合{2,3,5}的笛卡尔积,并返回结果集中每个元素的所有三个分量的乘积。 However, some numbers appear multiple times, ie 12 can be written as 2*2*3, 2*3*2, or 3*2*2. 但是,某些数字会多次出现,即12可写为2 * 2 * 3、2 * 3 * 2或3 * 2 * 2。 I would like to remove all but one instance of these duplicates. 我想删除这些重复项中的所有(除了一个)实例。

I know that this fundamentally a combinatorics problem, but this seems like there is probably a nice solution in Python that doesn't involve doing an extra pass over the list like I did here to compute some identifier for each element of the Cartesian product. 我知道这从根本上讲是一个组合问题,但这似乎是Python中可能有一个不错的解决方案,它不像我在此处为笛卡尔乘积的每个元素计算一些标识符那样,不需要对列表进行额外的传递。

您要combinations_with_replacement ,而不是product

itertools.combinations_with_replacement([x, y, z], 3)

Use a dict to map each unique product to the most recently seen tuple. 使用dict将每个唯一产品映射到最近看到的元组。

d = {reduce(operator.mul, f): f for f in flist}

If you would need to treat tuples that aren't permutations of each other as distinct elements, you'll need a more complicated key that incorporates a canonical representation of the tuple. 如果需要将不是彼此置换的元组视为不同的元素,则需要一个更复杂的键,该键包含元组的规范表示。

from operator import mul
d = {(tuple(sorted(f)), reduce(mul, f)): f for f in flist}

Actually, once you do that, you don't need to map the tuple/product pair to a tuple; 实际上,一旦这样做,就不需要将元组/产品对映射到元组。 you can just maintain a set of pairs: 您可以维护一组配对:

d = {(tuple(sorted(f)), reduce(mul, f)) for f in flist}

In any case, retrieving just the tuples is as simple as 在任何情况下,仅检索元组都非常简单

tuples = d.values()  # In the first two cases
tuples = {x for x,y in d} # In the third case

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM