rafaelcb21
rafaelcb21

Reputation: 13304

How to find the cumulative sum of numbers in a list by adding a constant value?

Is it possible to create with numpy or another lib with only 2 pieces of information, initial_value added with a constant_value, with the next value in the list using the previous value?

initial_value = 5
constant_value = 3
desired_list_size = 7

ll = [initial_value]

for i in range(desired_list_size-1):
    next_value = ll[i] + constant_value
    ll.append(next_value)

print(ll)
#[5, 8, 11, 14, 17, 20, 23, 26]

Upvotes: 0

Views: 180

Answers (2)

Wombatz
Wombatz

Reputation: 5458

As you specifically mentioned numpy:

import numpy as np

initial_value = 5
constant_value = 3
desired_list_size = 7

result = np.arange(desired_list_size) * constant_value + initial_value

This starts with a range from 0 to 7 (exclusive) then it multiplies each element by 3 and in the end it adds 5 to each element.

Note: the result size is actually equal to desired_list_size and not one larger as in your question.

Upvotes: 1

Ahasanul Haque
Ahasanul Haque

Reputation: 11134

>>> list(i* constant_value + initial_value for i in range(desired_list_size + 1))
[5, 8, 11, 14, 17, 20, 23, 26]

or even easier,

>>> list(range(initial_value, (desired_list_size + 2) * constant_value, constant_value))
[5, 8, 11, 14, 17, 20, 23, 26]

Upvotes: 1

Related Questions