编程语言
首页 > 编程语言> > 使用特定规则在Python中生成置换

使用特定规则在Python中生成置换

作者:互联网

假设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 …,令w = [1,2,3,4] …,并且max_weight =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的最佳组合

我的问题是

>生成所需排列的算法是什么?还是我可以生成排列的任何建议?
>由于元素数最多可以达到10000,并且如果分支的累加权重超过max_weight则计算将停止,因此在计算之前不必先生成所有排列. (1)中的算法如何动态生成排列?

解决方法:

使用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]

标签:knapsack-problem,permutation,python,algorithm
来源: https://codeday.me/bug/20191123/2064992.html