8
$\begingroup$

Consider the following function, which recursively splits a list into equal length sublists (the length of the list is assumed to be a power of the second argument):

repPartition[list_, n_]:=
  If[Length[list]<=n, list, repPartition[Partition[list, n], n]]

This function does what it is intended to do. However the recursion probably doesn't make this the fastest possible; also I have the feeling that I've probably missed a built-in function which allows me to do this directly.

Therefore my question: Can this definition be improved?

$\endgroup$
9
$\begingroup$

I would use Nest:

ClearAll[nestedPartition];
nestedPartition[list_, n_] :=
  With[{depth = Log[n, Length[list]]},
     Nest[Partition[#, n] &, list, depth - 1] /; IntegerQ[depth]
  ];

For example

nestedPartition[Range[32],2]
| improve this answer | |
$\endgroup$
  • $\begingroup$ This is at most just as fast as the recursive function. $\endgroup$ – paw Oct 1 '14 at 14:56
  • $\begingroup$ @paw Well, it doesn't have the $RecursionLimit limitation, for one thing. The speed can't be very significantly improved simply because, for most actual use cases, the main time will be spent inside Partition, in both cases. $\endgroup$ – Leonid Shifrin Oct 1 '14 at 14:59
  • $\begingroup$ I think it's save to assume that the OP doesn't want to partition a list bigger then 2^1024. $\endgroup$ – paw Oct 1 '14 at 15:05
  • $\begingroup$ I didn't know that you can put the condition inside a With. That's a nice way to get a restriction to valid lists. This alone is already a nice improvement to my version. $\endgroup$ – celtschk Oct 1 '14 at 15:06
  • $\begingroup$ @LeonidShifrin, nestedPartitionShifrin[Range@160, 2] is different from nestedPartitioncEltschk[Range@160, 2] $\endgroup$ – xyz Oct 1 '14 at 15:14
6
$\begingroup$

What about:

repPartition2[list_, n_] := 
  ArrayReshape[list, Table[n, {IntegerExponent[Length[list], n]}]]
| improve this answer | |
$\endgroup$
  • $\begingroup$ Looks great. The ArrayReshape documentation says introduced in 9.0, but unfortunately I'm stuck with 8.0, so I can't use that :-( But a +1, because I think this would actually be the perfect solution if only I could use it ... $\endgroup$ – celtschk Oct 1 '14 at 19:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.