使用特定规则在Python中生成置换
假设a=[a,B,C,D],每个元素都有一个权重w,如果选中则设置为1,否则设置为0。我想按以下顺序生成置换使用特定规则在Python中生成置换,python,algorithm,permutation,knapsack-problem,Python,Algorithm,Permutation,Knapsack Problem,假设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 让我们w=[1,2,3,4]对于项目A,B,C,D。。。最大重量=4。对于每个排列,如果累计重量超过最大重量,停止该排列的计算,移
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
让我们w=[1,2,3,4]对于项目A,B,C,D。。。最大重量=4。对于每个排列,如果累计重量超过最大重量,停止该排列的计算,移动到下一个排列。例如
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]是不超过最大重量4的最佳组合
我的问题是
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)
用于按选择过滤权重
>>> 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]
来自itertools导入的>>*
>>>压缩([1,2,3,4],[1,0,1,1])
>>>列表(压缩([1,2,3,4],[1,0,1,1]))
[1, 3, 4]
手动操作,您可以像这样做(不过我建议使用itertools
):
t=[1,0]
最大值=4
ans=[[i,j,k,l]如果i*1+j*2+k*3+l*4你保存了所有的置换吗?不,只存储当前的最佳置换(不超过最大权重)。因此,根据生成的顺序,[1,1,0,0]将被存储,然后[1,0,1,0]以后再换etc@twfx:你想用这个做什么?@Blender我感觉这是一个0/1背包暴力解决方案。对于第一个问题,请注意,你正在以二进制形式生成从2^n-1到0的数字。
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]]