-6

We are struggling with the following problem:
For example the following list, should be divided in m lists with the same order.

Lets say [9,7,6,5,2,10,8,4,3,1] with m=3 a few of the end results should be:

[[9],[7,6],[5,2,10,8,4,3,1]]
[[9,7],[6,5,2,10,8,4,3],[1]]
[[9,7,6,5],[2,10,8,4],[3,1]]

etc.

How can I achieve it?

Machavity
  • 30,841
  • 27
  • 92
  • 100
Stijn
  • 33
  • 6

2 Answers2

1
from itertools import combinations, permutations


perm=[]
index = [9,7,6,5,2,10,8,4,3,1]
perm.append(index)
M = 3
slicer = [x for x in combinations(range(1, len(index)), M - 1)]
slicer = [(0,) + x + (len(index),) for x in slicer]

result = [tuple(p[s[i]:s[i + 1]] for i in range(len(s) - 1)) for s in slicer for p in perm]
L Martens
  • 26
  • 2
0

Solution:

n= length of the list

k=m=3

def part(n, k):
 def _part(n, k, pre):
    if n <= 0:
        return []
    if k == 1:
        if n <= pre:
            return [[n]]
        return []
    ret = []
    for i in range(min(pre, n), 0, -1):
        ret += [[i] + sub for sub in _part(n-i, k-1, i)]
    return ret
 return _part(n, k, n)

import itertools
perm=[]
partitions=part(n, m)
for i in partitions:
    perm.append(list(itertools.permutations(i,m)))
perm1=list(itertools.chain.from_iterable(perm))  
y= [9,7,6,5,2,10,8,4,3]
new=[]
for i in perm1:
   k=0
   for j in i:
       new.append(list(y[k:k+j]))
       k=k+j
       if k==9:
         print(new)
         new=[]
Ravikiran
  • 571
  • 3
  • 10
  • Thanks for this solution, but do you have any idea how to use itertools.combinations?So we can get all possible combinations out of it? Since I tried a lot with it but it doesn't take order into account. – Stijn Dec 18 '18 at 10:54
  • Hey , I have updated the code which will print all the possible outputs. – Ravikiran Dec 18 '18 at 12:27