集合 python 的幂集和笛卡尔积 [英] Power set and Cartesian Product of a set python

查看:92
本文介绍了集合 python 的幂集和笛卡尔积的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到两个不同集合的笛卡尔积.我在网上找不到任何关于集合的笛卡尔积的信息,它要么是列表,要么是字典.

另外电源设置也很混乱.

我一直在使用的书中没有一个.

你们中的一位能不能指出我正确的方向.

解决方案

对于笛卡尔积,请查看 itertools.product.

对于 powerset,itertools 文档也给我们一个食谱:

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

例如:

<预><代码>>>>测试 = {1, 2, 3}>>>列表(电源组(测试))[(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]>>>列表(产品(测试,测试))[(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]

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.

Also power set is very confusing.

Neither one of these are in my book I have been using.

Could one of yall point me to the right direction.

解决方案

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)]

这篇关于集合 python 的幂集和笛卡尔积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆