假设a = [A,B,C,D],每个元素具有权重w,如果选择则设置为1,否则为0。我想按以下顺序生成排列
1,1,1,1
1,1,1,0
1,1,0,1
1,1,0,0
1,0,1,1
1,0,1,0
1,0,0,1
1,0,0,0
0,1,1,1
0,1,1,0
0,1,0,1
0,1,0,0
0,0,1,1
0,0,1,0
0,0,0,1
0,0,0,0
对于项目A,B,C,D ......和max_weight = 4,让w = [1,2,3,4]。对于每个排列,如果累加权重超过max_weight,则停止计算该排列,转到下一个排列。例如。
1,1,1 --> 6 > 4, exceeded, stop, move to next
1,1,1 --> 6 > 4, exceeded, stop, move to next
1,1,0,1 --> 7 > 4 finished, move to next
1,1,0,0 --> 3 finished, move to next
1,0,1,1 --> 8 > 4, finished, move to next
1,0,1,0 --> 4 finished, move to next
1,0,0,1 --> 5 > 4 finished, move to next
1,0,0,0 --> 1 finished, move to next
etc calculation continue
到目前为止,[1,0,1,0]是最佳组合,不超过max_weight 4
我的问题是
答案 0 :(得分:3)
使用itertools.product函数生成排列。
from itertools import *
w = [1,2,3,4]
max_weight = 4
for selection in product([1,0], repeat=len(w)):
accum = sum(compress(w, selection))
if accum > 4:
print '{} --> {} > {}, exceeded, stop, move to next'.format(selection, accum, max_weight)
else:
print '{} --> {} , finished, move to next'.format(selection, accum)
使用itertools.compress按选择过滤权重。
>>> from itertools import *
>>> compress([1,2,3,4], [1,0,1,1])
<itertools.compress object at 0x00000000027A07F0>
>>> list(compress([1,2,3,4], [1,0,1,1]))
[1, 3, 4]
答案 1 :(得分:0)
手动,你可以这样做(我建议尽管itertools
):
t = [1,0]
max = 4
ans = [[i,j,k,l] for i in t for j in t for k in t for l in t if i*1+j*2+k*3+l*4 <= max]
#[[1, 1, 0, 0],
# [1, 0, 1, 0],
# [1, 0, 0, 0],
# [0, 1, 0, 0],
# [0, 0, 1, 0],
# [0, 0, 0, 1],
# [0, 0, 0, 0]]