我想根据它的子集找到有效的算法。要为每个子集执行新条件。 例如:我有4个标志ABCD,每个子集将具有单独的条件。什么是解决以下条件的最有效算法。它可以轻松制作,但我想找到最有效的算法。是否已有解决此类问题的算法?
A B C D
0 0 0 0 Subset 1 Execute Condition 1
0 0 0 1 Subset 2 Execute Condition 2
0 0 1 0 Subset 3 Execute Condition 3
0 0 1 1 Subset 4 Execute Condition 4
0 1 0 0 Subset 5 Execute Condition 5
0 1 0 1 Subset 6 Execute Condition 6
0 1 1 0 Subset 7 Execute Condition 7
0 1 1 1 Subset 8 Execute Condition 8
1 0 0 0 Subset 9 Execute Condition 9
1 0 0 1 Subset 10 Execute Condition 10
1 0 1 0 Subset 11 Execute Condition 11
1 0 1 1 Subset 12 Execute Condition 12
1 1 0 0 Subset 13 Execute Condition 13
1 1 0 1 Subset 14 Execute Condition 14
1 1 1 0 Subset 15 Execute Condition 15
1 1 1 1 Subset 16 Execute Condition 16
答案 0 :(得分:0)
Bitmasking可用于生成所有子集。有四个值。因此,您有2 ^ 4个子集。你所要做的就是迭代这个掩码2 ^ 4次并用四个值中的每一个掩盖它。在每次迭代中,掩蔽的结果是给定值的子集。这是一个想法:
allSubsets = {}
for mask in range(1<<4):
subsets = []
for i in range(0,3):
val = mask & (1<<i)
if(val)
subsets.append(a[i]) # Individual subset. Here assume array a has 4 values. Can be just 1s and 0s as in your case.
allSubsets[mask] = subset #keep appending each generated subset
return allSubsets # Do your operation by iterating on each of these subsets