0

Similar questions have been asked before, but they answer the question "how to split a list into evenly sized chunks", not split a list into k groups, as evenly sized as possible:

Here is what I want to do:

For example For N = 4, and K = 3:
Return 3 lists, with the following elements from N
k1 = N1
k2 = N2
k3 = N3, N4

or N = 6, and K=4:
Return 4 lists, with the following elements from N
k1 = N1
k2 = N2
k3 = N3, N4
k4 = N5, N6

In python this can be represented as:

n = ["1","2","3","4","5","6"]
k = 4
print(solution(n,k))
$ ["1"]
$ ["2"]
$ ["3", "4"]
$ ["5", "6"]

An example is saying I have K=4 Processors and N = 6, tasks how do I evenly divide the tasks amongst the processors.

Here is a similar question written in C: How to share work roughly evenly between processes in MPI despite the array_size not being cleanly divisible by the number of processes?

The approach taken there is assign int(N/K) task across the "processors", and share the remainder.

I am wondering if there is a pythonic way of doing this.

UPF
  • 41
  • 3

1 Answers1

1

You could use numpy.array_split:

import numpy as np 

arr = range(6) 
np.array_split(arr, 4) 

>>[array([0, 1]), array([2, 3]), array([4]), array([5])]
manesioz
  • 798
  • 1
  • 9
  • 21