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

前端 未结 2 1489
臣服心动
臣服心动 2021-01-27 11:57

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 permuta

相关标签:
2条回答
  • 2021-01-27 12:35

    You want combinations_with_replacement, not product:

    itertools.combinations_with_replacement([x, y, z], 3)
    
    0 讨论(0)
  • 2021-01-27 13:00

    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
    
    0 讨论(0)
提交回复
热议问题