Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.soft-sys.math.mathematica > #8402
| From | Bill Rowe <readnews@sbcglobal.net> |
|---|---|
| Newsgroups | comp.soft-sys.math.mathematica |
| Subject | Re: Getting stuck with finding an elegant solution without global variables |
| Date | 2012-02-08 10:36 +0000 |
| Organization | Steven M. Christensen and Associates, Inc and MathTensor, Inc. |
| Message-ID | <jgtj6g$6fb$1@smc.vnet.net> (permalink) |
On 2/7/12 at 4:05 AM, fredrik.doberl@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.
Back to comp.soft-sys.math.mathematica | Previous | Next | Find similar | Unroll thread
Re: Getting stuck with finding an elegant solution without global variables Bill Rowe <readnews@sbcglobal.net> - 2012-02-08 10:36 +0000
csiph-web