5

列出集合的所有子集的numpy实现

 2 years ago
source link: https://allenwind.github.io/blog/10997/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Mr.Feng Blog

NLP、深度学习、机器学习、Python、Go

列出集合的所有子集的numpy实现

纯numpy实现的非递归方法。

考虑到集合中每个元素在子集中有两种状态,分别为存在与不存在,因此总共有2n2n种可能,每种可能0,1,2,…,2n−10,1,2,…,2n−1都可以用二进制表示,例如n=10n=10​时(元素个数,也是二进制的宽度),二进制表示为0001100100。因此获得对应关系,0表示元素不会出现在子集中,1表示出现在子集中。

利用这种对应关系,使用numpy的编程实现,

import numpy as np

def list_all_sub_groups(es):
n = len(es)
for i in range(2 ** n):
idx = (np.array(list(np.binary_repr(i, n))) == "1")
yield es[idx]

es = np.array(["a", "b", "c", "e", "f"])
for e in list_all_sub_groups(es):
print(e)

结果如下,

[]
['f']
['e']
['e' 'f']
['c']
['c' 'f']
['c' 'e']
['c' 'e' 'f']
['b']
['b' 'f']
['b' 'e']
['b' 'e' 'f']
['b' 'c']
['b' 'c' 'f']
['b' 'c' 'e']
['b' 'c' 'e' 'f']
['a']
['a' 'f']
['a' 'e']
['a' 'e' 'f']
['a' 'c']
['a' 'c' 'f']
['a' 'c' 'e']
['a' 'c' 'e' 'f']
['a' 'b']
['a' 'b' 'f']
['a' 'b' 'e']
['a' 'b' 'e' 'f']
['a' 'b' 'c']
['a' 'b' 'c' 'f']
['a' 'b' 'c' 'e']
['a' 'b' 'c' 'e' 'f']

转载请包括本文地址:https://allenwind.github.io/blog/10997
更多文章请参考:https://allenwind.github.io/blog/archives/


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK