Re: working with lists
- To: mathgroup at smc.vnet.net
- Subject: [mg113224] Re: working with lists
- From: Andrzej Kozlowski <akoz at mimuw.edu.pl>
- Date: Tue, 19 Oct 2010 05:56:41 -0400 (EDT)
- References: <201010180947.FAA00936@smc.vnet.net>
This uses pattern matching and recursion so it won't be particularly fast, but it seems to me the easiest way to program this sort of thing:
f[ls_List] /; ! MemberQ[Mod[ls, 3], 0] := ls
f[ls_List] :=
ls /. {v___, u_ /; Mod[u, 3] == 0, w___} :>
Flatten[{{v, 2 u}, f[{w} - 1]}]
In[5]:= f[{1,2,3,5,7}]
Out[5]= {1,2,6,4,12}
In[4]:= f[{1, 2, 3, 5, 7, 11, 12, 13, 14}]
Out[4]= {1,2,6,4,12,18,18,18,18}
Andrzej Kozlowski
On 18 Oct 2010, at 11:47, Sam Takoy 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
>
- References:
- working with lists
- From: Sam Takoy <sam.takoy@yahoo.com>
- working with lists