ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2019-11-23 04:07:39  阅读:251  来源: 互联网

标签:knapsack-problem permutation python algorithm


假设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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有