I have an array of the type:
import numpy as np
mi_array = np.array([1,2,3])
Now, given a certain starting value, for example 100, I would like to calculate the array that is formed by subtracting the subsequent value from the result of the previous subtraction. That is, I would like to get the result of:
100 - 1, 99 - 2, 97 - 3
That is, the array[99, 97, 94]
I have tried the following.
import numpy as np
a= np.array([1,2,3])
def resta_iterativa(value):
result = []
for i in a:
resta = value - i
result.append(resta)
return result
print(resta_iterativa(100))
The goal is to get a more efficient code, and one that works.
What you are proposing is equivalent to the following:
Therefore, you can make use of the fact
np.cumsum()
that it returns the cumulative sum of an array (that is, it returns a new one in which each element is equal to the cumulative sum of all the previous ones, which in your case will be the array [1 , 1+2, 1+2+3]), and simply subtract that result from 100:And you get what you were looking for:
Bonuses
Why didn't your code work? There are two fundamental reasons:
return
inside the loop, so after the first iteration you already returnresult
, which at that moment has a single element[99]
. Hereturn result
should be out of the loop[99, 98, 97]
because itvalue
's always 100, but you wanted it to go down as well. you needed to do thatvalue = value - i
Namely:
This will already work as you want, but it is much more inefficient than the above solution using
cumsum()
.