生成所有长度的所有排列

发布于 2024-09-30 09:22:08 字数 373 浏览 4 评论 0原文

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

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

依此类推并获得每个长度的所有排列?

编辑: 我将使用这个用 python 编写的,效果很好:

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

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?

EDIT:
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))  

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

惜醉颜 2024-10-07 09:22:08

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

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

从那里您应该能够使用网上许多代码示例中的任何一个来返回排列。

I think that would be all permutations of each subset.

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.

娇妻 2024-10-07 09:22:08

我建议从更简单的事情开始。假设 l 是一个包含 n 元素的列表。首先,你能编写一个函数来生成具有固定长度kl的所有排列吗?然后,您能否找到一种方法,使用不同的 k 值重复调用该函数,以生成长度为 0 的排列、长度为 1 的所有排列、长度为 2 的所有排列,依此类推,直到您得到n

I'd suggest starting with something simpler. Suppose l is a list with n elements. First, can you write a function to generate all permutations of l which have a fixed length k? Then, can you find a way to call that function repeatedly with different k values to generate the permutations of length 0, all permutations of length 1, all permutations of length 2, and so on until you get to n?

晨光如昨 2024-10-07 09:22:08

考虑生成字符串的所有排列的递归实现。如果您在构建子排列时存储它们,那么您将拥有您想要的所有排列。

在 erlang 中,作为起点(这是 3.3 Permutations 的修改版本)

perms([]) -> [[]];
perms(L) ->
  [ [H|T] || H <- L, T <- perms(L -- [H])]
  ++ [ [T] || H <- L, T <- perms(L -- [H]) ].

但请注意,这会给您留下重复项和大量空数组的数组,您必须删除这些数组才能使输出更漂亮。

Consider the recursive implementation of generating all permutations of a string. If you store the sub-permutations as you build them up, then you'll have all the ones you want.

In erlang, as a starting point (which is a modified version of 3.3 Permutations)

perms([]) -> [[]];
perms(L) ->
  [ [H|T] || H <- L, T <- perms(L -- [H])]
  ++ [ [T] || H <- L, T <- perms(L -- [H]) ].

but note that this leaves you with duplicates and lots of arrays of empty arrays that you'll have to remove to make the output prettier.

硪扪都還晓 2024-10-07 09:22:08

之前我提到过,我在 Python 中编写了一个可怕的 lambda 表达式,使用他们在 2.6 中添加的 bin() 整数到二进制字符串内置函数来生成序列的所有子集。

这是它的更丑陋的版本:

subsets = lambda s: (
    (s[x] for x,c in 
       enumerate("0" * (len(s)-len(bin(i)[2:])) + bin(i)[2:])
       if int(c)) 
     for i in range(0,2**len(s)
     )
)

但我注意到我可以通过简单调用字符串的 zfill() 来替换该表达式的 "0" * ... +" 部分code> 方法(感谢 SO 用户:gimel)。 :

subsets = lambda s: (
        [s[x] for x,c in 
              enumerate(bin(i)[2:].zfill(len(s)))
              if int(c)
              ]
        for i in range(0,2**len(s))
    )

尽管看起来很简单,但它是我所描述的一个相对简单的实现:给定表示从零到集合大小的任何整数的二进制字符串,屏蔽掉与二进制字符串中的零相对应的任何元素。外部(生成器)表达式仅涵盖了必要的范围,

如果我知道的话,我可能会想到使用带有两个参数的 itertools.permutations() 方法。查看该函数的 __doc__ 字符串 但是,我确实需要花一些时间来说服自己这两种方法都会给出相同的结果。

Earlier I mentioned that I concocted, in Python, a hideous lambda expression to generate all subsets of a sequence using the bin() integer to binary string built-in function that they added in 2.6.

Here's the uglier version of it:

subsets = lambda s: (
    (s[x] for x,c in 
       enumerate("0" * (len(s)-len(bin(i)[2:])) + bin(i)[2:])
       if int(c)) 
     for i in range(0,2**len(s)
     )
)

But I noticed that I can replace the "0" * ... +" portion of that expression with a simple call to the string's zfill() method (thanks SO User: gimel). So that becomes the slightly less odious:

subsets = lambda s: (
        [s[x] for x,c in 
              enumerate(bin(i)[2:].zfill(len(s)))
              if int(c)
              ]
        for i in range(0,2**len(s))
    )

This, despite its appearances, is a relatively simple implementation of what I described: given the binary string representing any integer from zero to the size of our set, mask out any of the elements corresponding to zeros in our binary string. That's the inner list comprehension. The outer (generator) expression simply covers the necessary range.

The OP's approach of using itertools.permutations() with two arguments is more elegant. I might have thought of it if I'd known to look at the __doc__ string for that function. However, I did have to spend a little time convincing myself that both approaches give the same results.

野の 2024-10-07 09:22:08

一般来说,长度为 n 的列表有 n!安排或排列。因此,对于多个长度,我们将有 n!(nk)!其中 k 为 0 < k<名词

In general a list of length n has n! arrangements or permutations. So with multiple lengths, we would have n!(n-k)! where k is 0 < k < n.

萌辣 2024-10-07 09:22:08

对于列列表 feature_cols,我们可以使用这个衬垫:

[combo for i in range(1, len(feature_cols) + 1) for combo in itertools.combinations(feature_cols, i) ]

这基本上是在做:

all_combinations = []
for i in range(1, len(feature_cols) + 1):
    for combo in itertools.combinations(feature_cols, i):
        all_combinations.append(combo)

例如

>>> feature_columns = ['TV', 'Radio', 'Newspaper']
>>> all_combinations = [combo for i in range(1, len(feature_cols) + 1) for combo in itertools.combinations(feature_cols, i) ]
>>> all_combinations
[('TV',),
 ('Radio',),
 ('Newspaper',),
 ('TV', 'Radio'),
 ('TV', 'Newspaper'),
 ('Radio', 'Newspaper'),
 ('TV', 'Radio', 'Newspaper')]

for a list of columns feature_cols, we can use this one liner:

[combo for i in range(1, len(feature_cols) + 1) for combo in itertools.combinations(feature_cols, i) ]

which is basically doing:

all_combinations = []
for i in range(1, len(feature_cols) + 1):
    for combo in itertools.combinations(feature_cols, i):
        all_combinations.append(combo)

e.g.

>>> feature_columns = ['TV', 'Radio', 'Newspaper']
>>> all_combinations = [combo for i in range(1, len(feature_cols) + 1) for combo in itertools.combinations(feature_cols, i) ]
>>> all_combinations
[('TV',),
 ('Radio',),
 ('Newspaper',),
 ('TV', 'Radio'),
 ('TV', 'Newspaper'),
 ('Radio', 'Newspaper'),
 ('TV', 'Radio', 'Newspaper')]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文