Re: working with lists

*To*: mathgroup at smc.vnet.net*Subject*: [mg113208] Re: working with lists*From*: Ray Koopman <koopman at sfu.ca>*Date*: Tue, 19 Oct 2010 05:53:41 -0400 (EDT)*References*: <i9h596$128$1@smc.vnet.net>

On Oct 18, 2:50 am, Sam Takoy <sam.ta... at yahoo.com> wrote: > Hi, > > I'm not very good at working with lists. May I ask for someone to > work out an example which has several elements of what I need to do. > > What's the best way to write a function f[list] that goes through > each element of the lest, doubles each element divisible by three > and reduces each of the following elements by 1. That is > > f[{ 1 2 3 5 7}] is { 1 2 6 4 12 } > > Many thanks in advance, > > Sam Here are two (of what I'm sure will be many) examples. The first requires you to recognize that Decrement has a higher precedence than Plus. The second avoids adding 'a' twice on each pass and is a tiny bit faster but is more convoluted, with one function nested inside another. In[1]:= f1[x_] := Block[{a = 0}, If[Mod[#+a,3]==0, 2(#+a--), #+a]& /@ x ]; f2[x_] := Block[{a = 0}, If[Mod[#,3]==0, a-- ; 2#, #]& [#+a]& /@ x ]; f1[{1,2,3,5,7}] f2[{1,2,3,5,7}] f1[Range@20] f2[Range@20] Out[3]= {1,2,6,4,12} Out[4]= {1,2,6,4,12} Out[5]= {1,2,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6} Out[6]= {1,2,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6}