[EMAIL PROTECTED] wrote: > > > > On Wed, 23 Jan 2008, William Stein wrote: > >> On Jan 23, 2008 4:12 PM, Jason Grout <[EMAIL PROTECTED]> wrote: >>> Does anyone know the best way to partition a list into sublists of a >>> specific length, similar to the Partition command in Mathematica? I'm >>> thinking of something like: >>> >>> sage: partition([1,2,3,4],2) >>> [[1,2],[3,4]] >>> sage: partition([1,2,3,4,5],2,pad=0) >>> [[1,2],[3,4],[5,0]] >>> >>> It seems like this is a problem that python would have solved millions >>> of years ago, but I can't find anything when searching online. I can >>> whip it up quickly, but I'm sure it's already been invented, which is >>> why I'm asking. >> Let me be the first of many to post a one liner: >> >> sage: def partition(v, n): >> ... return [v[n*i:n*i+n] for i in range(len(v)//n)] >> >> sage: partition([1,2,3,4],2) >> [[1, 2], [3, 4]] > > Let me be the first of many to post a counterexample: > sage: partition([1,2,3,4,5],2) > [[1, 2], [3, 4]] > > and a fix: > > sage: def partition(v,n): > ... return [v[i:i+n] for i in range(0,len(v),n)] > sage: partition([1,2,3,4,5],2) > [[1, 2], [3, 4], [5]]
And let me be the first of many to say that that was the solution that I finally found as I continued to search. Is there a nice, fast function that provides some of the pretty extensive functionality of the Partition function in Mathematica? Or how about even just a default padding, as in my example? See http://reference.wolfram.com/mathematica/ref/Partition.html Or is it time to write such a function? :) As it is, the one-liner above is all I need for now. Thanks, Jason --~--~---------~--~----~------------~-------~--~----~ To post to this group, send email to sage-devel@googlegroups.com To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/sage-devel URLs: http://www.sagemath.org -~----------~----~----~----~------~----~------~--~---