I'm having quite a hard time with the following. I would like to partition a list into a list of sub-lists, in such a way that the number n
of sub-lists is fixed.
For example, suppose I'm looking for a partition of size n=3
:
L = {1,2,3,4,5};
n = 3;
size = Ceiling[Length[L]/n]
Partition[L, size, size, {1,1}, {}]
{{1, 2}, {3, 4}, {5}}
Great! But now I run into problems when n=4
. Namely, the above method produces the same length 3 output. This is basically due to exhaustion of the original list L
.
My solution so far is to use an ad hoc if statement that takes an element from the first bucket:
L = {1,2,3,4,5};
n = 4;
size = Ceiling[Length[L]/n]
newL = Partition[L, size, size, {1, 1}, {}]
If[Length[newL] < n,
AppendTo[newL, {newL[[1, 1]]}];
newL[[1]] = newL[[1, 2 ;;]];
];
newL
{{2}, {3, 4}, {5}, {1}}
Is there a better way to do this?
Edit 1:
kguler's answer was great, but Kellen's solution definitely performs better for large inputs: (blue = kguler's bpF2
, red = Kellen's splitup
)
Thanks guys!
Edit 2:
I answered my own question below, because I found a nice one-liner solution which also improves performance.
p
of parts, so thatp(k-1)<n
and then just pick out the firstk-1
parts to be of sizep
, and throw everything into the last part. My answer will assume that you want parts of nearly-equal (off by one) size. $\endgroup$