生成所有长度的所有排列 [英] Generate all permutations of all lengths

查看:72
本文介绍了生成所有长度的所有排列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您将如何生成列表b(1,6,8,3,9,5)的所有可能排列,包括长度不同的排列?示例:

How would you generate all the possible permutations of list b(1,6,8,3,9,5) including ones of different length? Example:

List a = [1,2,3]
generateperms(a)
1,2,3
3,1,2
3,2,1
1,3,2
2,1,3
2,3,1
2,3
1,2
1,3
2,1
3,2
3,1

以此类推,得到每个长度的所有排列吗?

And so forth and getting all the permutarions of each length?

我将使用用python编写的代码,效果很好:

I'm just going to use this, written in python, works well enough:

import itertools  
a = ['a','b','c']  
for i in range(len(a)):  
    print list(itertools.permutations(a,i+1))  

推荐答案

我认为这将是每个子集的所有排列.

I think that would be all permutations of each subset.

返回子集的最简单方法是考虑从0(空集)到输入列表(完整集)长度的所有二进制整数.因此,您可以从0到2**(length(input))进行计数,并使用结果掩盖所有要从该特定子集中排除的元素.

The easiest way to return subsets is to consider all binary integers from 0 (the empty set) through the length of your input list (the complete set). So you count from 0 through and including 2**(length(input)) and use the results to mask off all elements to exclude from that particular subset.

从那里开始,您应该可以使用网上的许多代码示例中的任何一个来返回排列.

From there you should be able to use any of the many examples of code out on the 'net for returning permutations.

这篇关于生成所有长度的所有排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆