纯numpy实现的非递归方法。
考虑到集合中每个元素在子集中有两种状态,分别为存在与不存在,因此总共有$2^n$种可能,每种可能$0,1,2, \dots, 2^n-1$都可以用二进制表示,例如$n=10$时(元素个数,也是二进制的宽度),二进制表示为0001100100。因此获得对应关系,0表示元素不会出现在子集中,1表示出现在子集中。
利用这种对应关系,使用numpy的编程实现,
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 
 | 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)
 
 | 
结果如下,
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 
 | []['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/