Mathematica 9 is now available
Services & Resources / Wolfram Forums
-----
 /
MathGroup Archive
1995
*January
*February
*March
*April
*May
*June
*July
*August
*September
*October
*November
*December
*Archive Index
*Ask about this page
*Print this page
*Give us feedback
*Sign up for the Wolfram Insider

MathGroup Archive 1995

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: There must be a better way!

  • To: mathgroup at smc.vnet.net
  • Subject: [mg2342] Re: There must be a better way!
  • From: zizza at willamette.edu (Frank Zizza)
  • Date: Wed, 25 Oct 1995 02:13:25 -0400
  • Organization: Willamette University, Salem, OR, USA

In article <DGxuMB.G69 at wri.com> pehowland at taz.dra.hmg.gb () writes:
> 
> Hi.  I'm trying to write a function that partitions a list into
> segments of length given by another length. eg. 
> 	Given l1 = {A,B,C,D,E,F,G,H,I,J}
> 	and   l2 = {2,3,4,1}
> I want to be able to say
> 	In[1] := MyPartition[l1, l2]
> and get
> 	Out[1] = {{A,B}, {C,D,E}, {F,G,H,I}, {J}}
> 
> I've racked my brains, but have been unable to think of an elegant
> solution, but instead managed the following Fortran-like function:
> 
> MyPartition[list1_, list2_] :=
> Module[{ans,l},
> 	ans={};
> 	l = list1;
> 	Do	[
> 		AppendTo[ans, Take[l, list2[[i]]]];
> 		l = Drop[l, list2[[i]]],
> 		{i, Length[list2]}
> 		];
> 	ans
> 	]
> 
> Someone put me out of my misery!  How can I code this in a more  
efficient
> manner?!
> 
> Paul E Howland                                  Tel. +44 (0)1684 895767
> Long Range Ground Radar Sensors                 Fax. +44 (0)1684 896315
> LSC2 Division                                 Email.  
PEHOWLAND at DRA.HMG.GB
> Defence Research Agency
> St Andrews Road
> Malvern
> Worcestershire, WR14 3PS, UK
>  
=========================================================================
Try this.

janus> math
Mathematica 2.2 for NeXT
Copyright 1988-93 Wolfram Research, Inc.
 -- NeXT graphics initialized -- 

In[1]:= MyPartition[list1_, list2_] := 
        Map[ Take[ list1, #]&, 
             FoldList[ Plus, {1, First[list2]}, Partition[list2, 2, 1]
           ]                          
        ]

In[2]:= MyPartition[{A,B,C,D,E,F,G,H,I,J}, {2,3,4,1}]

Out[2]= {{A, B}, {C, D, E}, {F, G, H, I}, {J}}







  • Prev by Date: RE: There must be a better way!
  • Next by Date: Re: Re: Re: Bug in interpretation of mma Series[] command?
  • Previous by thread: RE: There must be a better way!
  • Next by thread: Re: There must be a better way!