Issue
I want to subtract a number x
from the first element of the array, and in case the first element in the array is smaller than x
I want to subtract the remaining amount from the second element of the array and so on.
I have tried this:
import numpy as np
x = 25
y = np.array([22, 30, 45])
result = np.copy(y)
for i in range(len(y)):
if y[i] < x:
result[i] = y[i] - x
x = x - y[i]
else:
result[i] = y[i] - x
x = x - y[i]
I get this result:
array([-3, 27, 72])
But I want to have
array([0, 27, 45])
Solution
In the
if
case, you should assign0
In the
else
case there must be abreak
to stop as all value to remove has been consumed
def sub_array(array, to_remove):
result = np.copy(array)
for i in range(len(array)):
if array[i] < to_remove:
result[i] = 0
to_remove -= array[i]
else:
result[i] = array[i] - to_remove
break
return result
print(sub_array(np.array([10, 10, 10]), 39)) # [0 0 0]
print(sub_array(np.array([10, 10, 10]), 29)) # [0 0 1]
print(sub_array(np.array([10, 10, 10]), 19)) # [0 1 10]
print(sub_array(np.array([10, 10, 10]), 9)) # [1 10 10]
Answered By - azro
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.