2

Suppose

L=[1,2,3...8]

What I need is this

   [
[[1,2,3,5],[4,6,7,8]] , 
[[1 2 4 7] [3,5,6,8]] ,
..... ]

The no of elements in list should be user depended and lists be disjoint . I am really having no clue how to do that in python

yatu
  • 86,083
  • 12
  • 84
  • 139
Yash Singhal
  • 357
  • 1
  • 2
  • 8
  • Does this answer your question? [How to generate all permutations of a list?](https://stackoverflow.com/questions/104420/how-to-generate-all-permutations-of-a-list) – pppery Oct 06 '20 at 02:36

1 Answers1

4

IIUC obtain the permutations of the range and split the list into two chunks on each iteration:

from itertools import permutations

l = range(1,9)
n = len(l)//2

[[[*r[:n]],[*r[n:]]] for r in permutations(l)]
[[[1, 2, 3, 4], [5, 6, 7, 8]],
 [[1, 2, 3, 4], [5, 6, 8, 7]],
 [[1, 2, 3, 4], [5, 7, 6, 8]],
 [[1, 2, 3, 4], [5, 7, 8, 6]],
 [[1, 2, 3, 4], [5, 8, 6, 7]],
 [[1, 2, 3, 4], [5, 8, 7, 6]],
 ...

To split into chunks of arbitrary size (say 4), you could use a nested list comprehension. Keep in mind that for larger sizes, you'll end up with a huge amount of permutations. You can use a generator and just take the first n using itertools.islice:

from itertools import islice

l = range(1,25)
n = len(l)
s = n//4
list(islice(([r[i:i+s] for i in range(0,n,s)] for r in permutations(l)), 5))
[[(1, 2, 3, 4, 5, 6),
  (7, 8, 9, 10, 11, 12),
  (13, 14, 15, 16, 17, 18),
  (19, 20, 21, 22, 23, 24)],
 [(1, 2, 3, 4, 5, 6),
  (7, 8, 9, 10, 11, 12),
  (13, 14, 15, 16, 17, 18),
  (19, 20, 21, 22, 24, 23)],
 [(1, 2, 3, 4, 5, 6),
  (7, 8, 9, 10, 11, 12),
  (13, 14, 15, 16, 17, 18),
  (19, 20, 21, 23, 22, 24)],
 ...
yatu
  • 86,083
  • 12
  • 84
  • 139