Reputation: 13
When assigning a value from an array to another one, the array on the right hand side changes. Could you point me towards the possible mistake that I make?
The code below finds longest increasing sequence and I have the problem with the last line yy[-1] = y[n]
. Whenever this line executed a value in y also changes.
import numpy as np
p = np.array([466, 5500, 2615, 4056, 2196, 4254, 2987, 5125, 1060, 7344, 2990])
y = p.argsort()
yy = y[-2:]
yy = yy[::-1]
n = len(y)-2
while(n>0):
n = n-1
if (y[n] < yy[-1]):
yy = np.append(yy,y[n])
if ((y[n] > yy[-1]) & (y[n] < yy[-2])):
yy[-1] = y[n]
Upvotes: 1
Views: 594
Reputation: 31494
As you can read in the numpy guide:
All arrays generated by basic slicing are always views of the original array.
This means that the y
and yy
are basically different views of the same underlying data structure. So when you change the first you are also changing the second one and vice versa.
The easiest thing is to copy the array after slicing it, turning the following line:
yy = y[-2:]
into:
yy = y[-2:].copy()
Upvotes: 2