Re: Map function which adds last two numbers of a list

• To: mathgroup at smc.vnet.net
• Subject: [mg73567] Re: Map function which adds last two numbers of a list
• From: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>
• Date: Thu, 22 Feb 2007 04:28:11 -0500 (EST)
• Organization: The Open University, Milton Keynes, UK
• References: <ergqrb\$jg0\$1@smc.vnet.net>

```Christopher Pike wrote:
> Hi,
>   Consider this:
>
> z = {{1,4,5,6},{7,8,9,1},{1,2,4,3}}
>
> I'd like to Map a function onto z which would replace the last two items
> with their sum:
>
> {{1,4,11},{7,8,10},{1,2,7}}
>
> I could easily use the Table command to construct this new table, but it
> would be nicer if I new how to Map some function on z that would produce
> the same result.
>
> Any suggestions.
>
> Thanks, Chris Pike
>

Hi Chris,

You could use a transformation rule as in

In[1]:=
z = {{1, 4, 5, 6}, {7, 8, 9, 1}, {1, 2, 4, 3}};

In[2]:=
z /. {u___, v_, (t_)?NumberQ} -> {u, v + t}

Out[2]=
{{1, 4, 11}, {7, 8, 10}, {1, 2, 7}}

And here is a version with a pure function mapped over the list x

In[3]:=
(Flatten[{Drop[#1, -2], Plus @@ Take[#1, -2]}] & ) /@ z

Out[3]=
{{1, 4, 11}, {7, 8, 10}, {1, 2, 7}}

Regards,
Jean-Marc

```

• Prev by Date: Re: Re: Creating a Listable Function
• Next by Date: Re: Approximate/asymptotic factorization
• Previous by thread: Re: Map function which adds last two numbers of a list
• Next by thread: Re: Map function which adds last two numbers of a list