所有排列的数字都有替换

时间:2014-03-21 03:39:52

标签: python r perl

我想在长度为4的向量中生成0,1,2和#的所有可能组合。组合顺序无关紧要,即11000101,0011,1010相同。所以我只想选择一个值,即' 1100'。你能告诉我怎么用python / perl。

0000
1111
1000
2111
''''
''''

我尝试使用python的itertools.product但得到几个repeat.Thanks

8 个答案:

答案 0 :(得分:5)

这是使用Algorithm::Combinatorics

的Perl选项
use strict;
use warnings;
use Algorithm::Combinatorics qw/combinations_with_repetition/;

print "@$_\n" for combinations_with_repetition( [ 0 .. 2 ], 4 );

输出:

0 0 0 0
0 0 0 1
0 0 0 2
0 0 1 1
0 0 1 2
0 0 2 2
0 1 1 1
0 1 1 2
0 1 2 2
0 2 2 2
1 1 1 1
1 1 1 2
1 1 2 2
1 2 2 2
2 2 2 2

答案 1 :(得分:3)

一种方法可以是:

for i in range(0, 5):
  for j in range (0,5-i):
   print '0'*i+'1'*j+'2'*(4-i-j)+'\n'

答案 2 :(得分:3)

在R中,您可以执行以下操作:

x <- 0:2
out <- unique(t(apply(
   do.call(expand.grid,replicate(4,x,simplify=FALSE)),
   1,
   sort)))

      [,1] [,2] [,3] [,4]
 [1,]    0    0    0    0
 [2,]    0    0    0    1
 [3,]    0    0    0    2
 [4,]    0    0    1    1
 [5,]    0    0    1    2
 [6,]    0    0    2    2
 [7,]    0    1    1    1
 [8,]    0    1    1    2
 [9,]    0    1    2    2
[10,]    0    2    2    2
[11,]    1    1    1    1
[12,]    1    1    1    2
[13,]    1    1    2    2
[14,]    1    2    2    2
[15,]    2    2    2    2

答案 3 :(得分:1)

您可以使用itertools.product()并将所有值附加到列表中,然后删除重复项,只要您不缺少某些值即可。以下是使用list(set(mylist))删除重复项的方法:

>>> values = []
>>> values.append(8)
>>> values.append(9)
>>> values.append(9)
>>> values.append(2)
>>> values.append(8)
>>> values.append(3)
>>> values
[8, 9, 9, 2, 8, 3]
>>> values = list(set(values))
>>> values
[8, 9, 2, 3]

答案 4 :(得分:1)

1)最快。使用gtools

的R解决方案
gtools::combinations(3, 4, repeats.allowed=TRUE)-1

2)更快。使用partitions

的R解决方案
t(apply(partitions::compositions(4,3),2,function(d) rep(c(0,1,2),d)))

3)慢一点。使用prob

的R解决方案
prob::urnsamples(c(0,1,2), size = 4, replace=TRUE)

答案 5 :(得分:0)

In [91]: for i in itertools.combinations_with_replacement('012', 4): print ''.join(i)
0000
0001
0002
0011
0012
0022
0111
0112
0122
0222
1111
1112
1122
1222
2222

答案 6 :(得分:0)

这是一种Python方法:

from itertools import combinations

def perm(chars, length):
    s = ''.join([c * length for c in list(chars)])
    combs = combinations(s, length)
    combs = [''.join(comb) for comb in combs]
    combs = list(set(combs))
    combs.sort()
    return combs

for x in perm('012', 4):
    print x

输出:

0000
0001
0002
0011
0012
0022
0111
0112
0122
0222
1111
1112
1122
1222
2222

答案 7 :(得分:0)

使用Math::Combinatorics

的Perl解决方案
use Math::Combinatorics;

use strict;
use warnings;

my $o = Math::Combinatorics->new(
    count     => 4,
    data      => [0..2],
    frequency => [4,4,4],
);

while (my @x = $o->next_multiset()) {
    print "@x\n";
}

输出:

2 2 2 1
2 2 2 0
2 2 2 2
2 2 1 1
2 2 1 0
2 2 0 0
2 1 1 1
2 1 1 0
2 1 0 0
2 0 0 0
1 1 1 0
1 1 1 1
1 1 0 0
1 0 0 0
0 0 0 0
相关问题