Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate a sequence keeping previous element in next element python

Tags:

python

I would like to generate a sequence in a list, I know how to do this using a for loop, but if I wanted to generate the list such that the previously generated element was included in the next element, how would I do this? I am very unsure

i.e generate the list such that its items were:

where x is just a symbol

[x,(x)*(x+1),(x)*(x+1)*(x+2)]

rather than [x,x+1,x+2]

Any help greatly appreciated!

like image 575
user124123 Avatar asked Jul 13 '26 08:07

user124123


1 Answers

I like to use a generator for this sort of thing.

def sequence(x, N):
    i = 0
    result = 1
    while i < N:
        result *= (x + i)
        i += 1
        yield result

>>> list(sequence(5, 10))
[5, 30, 210, 1680, 15120, 151200, 1663200, 19958400, 259459200, 3632428800L]

If you have numpy installed, this is faster:

np.multiply.accumulate(np.arange(x, x + N))
like image 169
Dan Allan Avatar answered Jul 14 '26 22:07

Dan Allan