使用特定规则在Python中生成置换
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了使用特定规则在Python中生成置换,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1564字,纯文字阅读大概需要3分钟。
内容图文
![使用特定规则在Python中生成置换](/upload/InfoBanner/zyjiaocheng/658/c919202f400c43608d2e20bae7731189.jpg)
假设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]
内容总结
以上是互联网集市为您收集整理的使用特定规则在Python中生成置换全部内容,希望文章能够帮你解决使用特定规则在Python中生成置换所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。