Reputation: 81
I want to build a list from a seed in such a way:
seed, seed*weight - seed*weight**2
, and so on, where the previous number is the seed for the next.
so with seed
of .5
and weight
of 3
we would get
.5, -4, 24.0
and so on
This is what I thought would work:
from itertools import accumulate, repeat
relationship = lambda seed, weight: seed*weight - seed*weight**2
seed = .5
weight = 3
inputs = list(repeat(seed,10))
first = [x for x in accumulate(inputs, relationship)]
Is the problem that the inputs list creates a list of .5
s, instead of populating the list forward with numbers that I want?
Upvotes: 0
Views: 428
Reputation: 104762
Your accumulate
call doesn't use the weight
variable you've declared at all. Rather, it uses the first value from inputs
as the first seed
(which is as intended), and all the other values as weights (not what is intended).
You could make it work with a different inputs
list:
inputs = [seed] + [weight]*10
results = list(accumulate(inputs, relationships))
But I'm not sure accumulate
is really the best way to solve this problem. I'd think it would be more natural to solve the problem in another way, such as with an infinite generator function:
def gen(seed, weight):
while True:
seed = seed * weight - seed * weight**2
yield seed
Since the series is a simple geometric progression (multiplying by weight - weight**2
each step), you could also write a function to calculate each value from a closed-form equation:
def calc(seed, weight, n):
factor = weight - weight**2
return seed * factor**(n+1)
Upvotes: 1