Power set and Cartesian Product of a set python

后端 未结 1 1814
感动是毒
感动是毒 2020-12-02 00:07

I am trying to find the cartesian product of two different sets. I can not find anything on the web about cartesian products of sets it\'s either of list or dictionaries.

相关标签:
1条回答
  • 2020-12-02 00:57

    For the Cartesian product, check out itertools.product.

    For the powerset, the itertools docs also give us a recipe:

    def powerset(iterable):
        "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
        s = list(iterable)
        return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
    

    For example:

    >>> test = {1, 2, 3}
    >>> list(powerset(test))
    [(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]
    >>> list(product(test, test))
    [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
    
    0 讨论(0)
提交回复
热议问题