Re: A NewBie Question

• To: mathgroup at smc.vnet.net
• Subject: [mg53655] Re: A NewBie Question
• From: Paul Abbott <paul at physics.uwa.edu.au>
• Date: Fri, 21 Jan 2005 06:37:01 -0500 (EST)
• Organization: The University of Western Australia
• References: <csl14p\$6s5\$1@smc.vnet.net>
• Sender: owner-wri-mathgroup at wolfram.com

```In article <csl14p\$6s5\$1 at smc.vnet.net>, Zhe Hu <iamhuzhe at gmail.com>
wrote:

> Is there a way to take parts of a list as follows:
>
> takeParts[{a,b,c,d,e,f,g,h,i}, {2,3,4}]
>
> {{a,b}, {c,d,e}, {f,g,h,i}}

This is an extension of the functionality provided by Partition.

> A tedious way might be transforming {2, 3, 4} into {{1,2}, {3,5}, {6,
> 9}} (by Fold) and then Part/@ onto it. Is there a simpler way to do
> it?

The best that I can come up with -- which is essentially the idea that
you have outlined -- but borrowing the use of Pad from Dr Bob, is

PartitionList[x_, i_] := Module[{n = FoldList[Plus, 0, i]},
PadRight[x, Last[n], x][[#]] & /@ (Most[n] + Range /@ i)]

This works fine on your example:

PartitionList[{a,b,c,d,e,f,g,h,i},{2,3,4}]

{{a, b}, {c, d, e}, {f, g, h, i}}

but it also handles the case where the sum of the length of the parts
does not coincide with the length of the list. For example,

PartitionList[{a,b,c,d,e,f,g,h,i},{2,3}]

{{a, b}, {c, d, e}}

and

PartitionList[{a,b,c,d,e,f,g,h,i},{2,3,4,0,7}]

{{a, b}, {c, d, e}, {f, g, h, i}, {}, {a, b, c, d, e, f, g}}

Cheers,
Paul

--
Paul Abbott                                   Phone: +61 8 6488 2734
School of Physics, M013                         Fax: +61 8 6488 1014
The University of Western Australia      (CRICOS Provider No 00126G)
35 Stirling Highway
Crawley WA 6009                      mailto:paul at physics.uwa.edu.au
AUSTRALIA                            http://physics.uwa.edu.au/~paul

```

• Prev by Date: Re: element selection
• Next by Date: Re: ShowLegend....
• Previous by thread: Re: A NewBie Question
• Next by thread: Function Fitting To 3D Data