Re: Q: Recursion on a list
- To: mathgroup at smc.vnet.net
- Subject: [mg28903] Re: [mg28886] Q: Recursion on a list
- From: BobHanlon at aol.com
- Date: Fri, 18 May 2001 01:13:06 -0400 (EDT)
- Sender: owner-wri-mathgroup at wolfram.com
The elements of a list are designated by r[[n]], i.e., with Part[r, n], not r[n], which is a function r evaluated for the argument n. To generate the complete new list f[r_List] := FoldList[#1*(1+#2)&, 1, r]; However, to calculate an element of the new list without calculating and storing the whole new list g[r_List, n_Integer?NonNegative] := Times @@ (1+Take[r, n]); r = {r1, r2, r3, r4, r5}; f[r] {1, r1 + 1, (r1 + 1)*(r2 + 1), (r1 + 1)*(r2 + 1)*(r3 + 1), (r1 + 1)*(r2 + 1)*(r3 + 1)* (r4 + 1), (r1 + 1)*(r2 + 1)* (r3 + 1)*(r4 + 1)*(r5 + 1)} g[r, 4] (r1 + 1)*(r2 + 1)*(r3 + 1)*(r4 + 1) f[r] == Table[g[r, k], {k, 0, Length[r]}] True For a large list r = Table[2Random[]-1, {10000}]; Last[f[r]] == g[r, Length[r]]//Timing {0.9166666666665151*Second, True} Bob Hanlon In a message dated 2001/5/17 5:13:35 AM, mscmsc at mediaone.net writes: >I'm looking for an efficient method (i.e., with the use of an explicit >loop) >for the following problem. I am working with large lists (several thousand >elements) of data. Denote one such list r. I would like to define a new >list >x such that: > > >x[0] = 1.0 > >x[t] = x[t-1]*(1.0 + r[t]) > >Can anyone suggest an efficient way? >