MathGroup Archive 2012

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

Search the Archive

Re: Getting stuck with finding an elegant solution without global variables

  • To: mathgroup at smc.vnet.net
  • Subject: [mg124825] Re: Getting stuck with finding an elegant solution without global variables
  • From: Bill Rowe <readnews at sbcglobal.net>
  • Date: Wed, 8 Feb 2012 05:32:34 -0500 (EST)
  • Delivered-to: l-mathgroup@mail-archive0.wolfram.com

On 2/7/12 at 4:05 AM, fredrik.doberl at gmail.com (Fredob) wrote:

>I am trying to find an elegant solution, i.e. without a global
>variable to the following problem:

>Given a list, e.g. {1,2,3,4}, create a new list where each element
>is a function of the "i th" element and the rest of the list, e.g.

Take a look at Nest or NestList. For example, the following
returns the sum of element i through the end of the list:

In[4]:= NestList[{Total[Last@#], #[[-1, 2 ;;]]} &, {Range[4]},
4][[2 ;;, 1]]

Out[4]= {10,9,7,4}

>Branch[Elem_, List_] := Elem + Cases[List, Except[Elem]]
>
>The the result would be {{3, 4, 5}, {3, 5, 6}, {4, 5, 7}, {5, 6, 7}}

In[5]:= branch[elem_, list_] := elem + Cases[list, Except[elem]]

In[6]:= NestList[{branch[#[[-1, 1]], {1, 2, 3, 4}], #[[-1, 2
;;]]} &,
            {Range[4]}, 4][[2 ;;, 1]]

Out[6]= {{3, 4, 5}, {3, 5, 6}, {4, 5, 7}, {5, 6, 7}}

Note, I changed your function branch to start with lower case
letters. It won't do to have a variable named List when
Mathematica has a built in function named List. Even if
Mathematica can handle things correctly, using a variable name
like this will make your code more difficult to understand.




  • Prev by Date: Something other than PlotStyle to change look of graphs
  • Next by Date: Re: Front end won't start on win7 64
  • Previous by thread: Re: Getting stuck with finding an elegant solution without global variables
  • Next by thread: Re: Getting stuck with finding an elegant solution without global variables