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

删除回忆录丶 提交于 2019-12-31 06:43:25

问题


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. However, some numbers appear multiple times, i.e. 12 can be written as 2*2*3, 2*3*2, or 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.


回答1:


You want combinations_with_replacement, not product:

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



回答2:


Use a dict to map each unique product to the most recently seen tuple.

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


来源:https://stackoverflow.com/questions/44958480/cartesian-product-of-sets-where-no-elements-are-identical-under-permutations-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!