在 Python 的排列下没有相同元素的集合的笛卡尔积
Cartesian Product of Sets where No Elements are Identical under Permutations in Python
我有一些集我想对其进行笛卡尔积,效果很好。但是,我想删除这个新集合中在元素排列下相同的所有元素。
例如取下面的代码:
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)
此代码计算集合 {2,3,5} 的笛卡尔积和结果集中每个元素的所有三个分量的乘积 returns。但是,有些数字会出现多次,例如 12 可以写成 2*2*3、2*3*2 或 3*2*2。我想删除所有这些重复项中的一个实例。
我知道这基本上是一个组合问题,但这似乎在 Python 中可能有一个不错的解决方案,它不涉及像我在这里所做的那样额外传递列表来计算一些标识符对于笛卡尔积的每个元素。
使用 dict
将每个唯一产品映射到最近看到的元组。
d = {reduce(operator.mul, f): f for f in flist}
如果您需要将不是彼此排列的元组视为不同的元素,您将需要一个包含元组规范表示的更复杂的键。
from operator import mul
d = {(tuple(sorted(f)), reduce(mul, f)): f for f in flist}
实际上,一旦你这样做了,你就不需要将 tuple/product 对映射到一个元组;你可以只维护一组对:
d = {(tuple(sorted(f)), reduce(mul, f)) for f in flist}
无论如何,只检索元组就像
一样简单
tuples = d.values() # In the first two cases
tuples = {x for x,y in d} # In the third case
你想要 combinations_with_replacement
,而不是 product
:
itertools.combinations_with_replacement([x, y, z], 3)
我有一些集我想对其进行笛卡尔积,效果很好。但是,我想删除这个新集合中在元素排列下相同的所有元素。
例如取下面的代码:
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)
此代码计算集合 {2,3,5} 的笛卡尔积和结果集中每个元素的所有三个分量的乘积 returns。但是,有些数字会出现多次,例如 12 可以写成 2*2*3、2*3*2 或 3*2*2。我想删除所有这些重复项中的一个实例。
我知道这基本上是一个组合问题,但这似乎在 Python 中可能有一个不错的解决方案,它不涉及像我在这里所做的那样额外传递列表来计算一些标识符对于笛卡尔积的每个元素。
使用 dict
将每个唯一产品映射到最近看到的元组。
d = {reduce(operator.mul, f): f for f in flist}
如果您需要将不是彼此排列的元组视为不同的元素,您将需要一个包含元组规范表示的更复杂的键。
from operator import mul
d = {(tuple(sorted(f)), reduce(mul, f)): f for f in flist}
实际上,一旦你这样做了,你就不需要将 tuple/product 对映射到一个元组;你可以只维护一组对:
d = {(tuple(sorted(f)), reduce(mul, f)) for f in flist}
无论如何,只检索元组就像
一样简单tuples = d.values() # In the first two cases
tuples = {x for x,y in d} # In the third case
你想要 combinations_with_replacement
,而不是 product
:
itertools.combinations_with_replacement([x, y, z], 3)