0

I want to make a series using Numpy. For example, starting with the value n = 2 I want to create the series:

terms = numpy.array([2, 6, 24, 120, 720,...])

where each successive term multiplies the previous term by the first term in the series, added to an incrementing index. For example, the above would be

terms[1] = terms[0] * (terms[0] + 1)
terms[2] = terms[1] * (terms[0] + 2)
terms[3] = terms[2] * (terms[0] + 3)
terms[4] = terms[3] * (terms[0] + 4)

Can this be done with Numpy? If not, what is the cleanest way that this can be done without a for-loop?

J_code
  • 356
  • 1
  • 5
  • 17

1 Answers1

2

You could use np.accumulate:

import numpy as np

size  = 5
n     = 2
terms = np.multiply.accumulate(np.arange(size) + n)

[  2   6  24 120 720]

You can also do that without numpy (albeit slower):

from itertools import accumulate

size  = 5
n     = 2
terms = [*accumulate(range(n,size+n),lambda a,b:a*b)]

[2, 6, 24, 120, 720]
Alain T.
  • 40,517
  • 4
  • 31
  • 51
  • Thanks for the elegant solution. Not sure why the individual made the post above earlier, closed the question promptly disappeared. My original question clearly had a solution...yours! – J_code Mar 19 '21 at 22:35