1

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]
3
  • I haven't read your code with due attention, but from the top of my head it seems like the problem occurs since NumPy arrays return lightweight wrappers when sliced, not new arrays. Hence yy and y are different views of the same array. Hence all operations on shared positions effect both y and yy Commented Aug 6, 2015 at 8:50
  • But then you've got np.append there, that does return a new array at some point. BTW, using np.append in a loop is highly inefficient. If you really need fast lightweight dynamic C-arrays with in-place append, use array.array. Just convert it to a NumPy array once the loop is over, if you need special NumPy functionality. Commented Aug 6, 2015 at 8:59
  • @EliKorvigo Thanks for the comments for improvement Commented Aug 6, 2015 at 10:08

1 Answer 1

2

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.