0

How to create a list with n-size non-repeating sublists from given list? I think the example will explain a lot.

given_list = [1, 2, 3, 4, 5]
n = 3
desired_list = [[1,2,3], [1,2,4], [1,2,5], [1,3,4], [1,3,5], [1,4,5], [2,3,4], [2,3,5], [2,4,5], [3,4,5]]

EDIT: I forgot to add some important combinations

  • 4
    Possible duplicate of [Making all possible combinations of a list](https://stackoverflow.com/questions/8371887/making-all-possible-combinations-of-a-list) – sahasrara62 Jun 14 '19 at 07:21
  • Something like this will do `itertools.permutations(given_list, 3)` – Mikku Jun 14 '19 at 07:23

2 Answers2

2

Not sure if you want combinations or permutations, so here are both:

Permutations

You can use permutations from itertools to find all permutations of a given list:

from itertools import permutations

given_list = [1, 2, 3, 4, 5]
n = 3

print([list(i) for i in permutations(given_list, n)])

Output:

[[1, 2, 3], [1, 2, 4], [1, 2, 5], [1, 3, 2], [1, 3, 4], [1, 3, 5], [1, 4, 2], [1
, 4, 3], [1, 4, 5], [1, 5, 2], [1, 5, 3], [1, 5, 4], [2, 1, 3], [2, 1, 4], [2, 1
, 5], [2, 3, 1], [2, 3, 4], [2, 3, 5], [2, 4, 1], [2, 4, 3], [2, 4, 5], [2, 5, 1
], [2, 5, 3], [2, 5, 4], [3, 1, 2], [3, 1, 4], [3, 1, 5], [3, 2, 1], [3, 2, 4],
[3, 2, 5], [3, 4, 1], [3, 4, 2], [3, 4, 5], [3, 5, 1], [3, 5, 2], [3, 5, 4], [4,
 1, 2], [4, 1, 3], [4, 1, 5], [4, 2, 1], [4, 2, 3], [4, 2, 5], [4, 3, 1], [4, 3,
 2], [4, 3, 5], [4, 5, 1], [4, 5, 2], [4, 5, 3], [5, 1, 2], [5, 1, 3], [5, 1, 4]
, [5, 2, 1], [5, 2, 3], [5, 2, 4], [5, 3, 1], [5, 3, 2], [5, 3, 4], [5, 4, 1], [
5, 4, 2], [5, 4, 3]]

Combinations

And you can use combinations from itertools to find all the combinations of a given list:

from itertools import combinations

given_list = [1, 2, 3, 4, 5]
n = 3

print([list(i) for i in combinations(given_list, n)])

Output:

[[1, 2, 3], [1, 2, 4], [1, 2, 5], [1, 3, 4], [1, 3, 5], [1, 4, 5], [2, 3, 4], [2
, 3, 5], [2, 4, 5], [3, 4, 5]]
funie200
  • 3,688
  • 5
  • 21
  • 34
  • 1
    @funie200 This solution with combinations is what I was looking for. Brilliant and simple! Thanks. Devesh, as funie200 said, in hurry I forgot to write some combs – Radosław Hryniewicki Jun 14 '19 at 07:40
0

A fast implementation of permutations:

    sub perm {
      my ($init,$k) = @_;
      my $n=length($init); my $dn=$n;
      my $out=""; my $m=$k;
      for (my $i=0;$i<$n;$i++) {
        my $ind=$m % $dn;  
        $out.=substr($init,$ind,1);
        $m=$m / $dn;  
        $dn--;
        substr($init,$ind,1,substr($init,$dn,1));
      }
      return $out
    }

k = 0 .. length(init)-1; each k giving an unique permutation, seemly randomly. to calculate the factorial length(init)!

     sub fac {
       my ($f) = @_;
       my $fac=1; while ($f>1) { $fac*=$f; $f-- } return $fac
     }