1

For example, how would you do this sequence of operations on a np 1D array, x:

  1. [1,2,3,4,5,6,7,8]

  2. [8,7,6,5,4,3,2,1]

  3. [7,8,5,6,3,4,1,2]

The transition from state 1 to state 2 can be done with numpy.flip(x):

x = numpy.flip(x)

How can you go from this intermediate state to the final state, in which each 'pair' of positions switches positions

Notes: this is a variable length array, and will always be 1D

3 Answers 3

1

It is assumed that the length is always even. At this time, you only need to reshape, reverse and flatten:

>>> ar = np.arange(1, 9)
>>> ar.reshape(-1, 2)[::-1].ravel()
array([7, 8, 5, 6, 3, 4, 1, 2])

This always creates a copy, because the elements in the original array cannot be continuous after transformation, but ndarray.ravel() must create a continuous view.

If it is necessary to transition from state 2 to state 3:

>>> ar = ar[::-1]
>>> ar    # state 2
array([8, 7, 6, 5, 4, 3, 2, 1])
>>> ar.reshape(-1, 2)[:, ::-1].ravel()
array([7, 8, 5, 6, 3, 4, 1, 2])
Sign up to request clarification or add additional context in comments.

Comments

0

This should work (assumin you have a even number of elements, otherwise you might want to check this before)

x = x.reshape((len(x)//2, 2)) #split in two wolumns
x[:,0], x[:,1] = x[:,1], x[:,0].copy() # switch the columns
x = x.reshape(2*len(x)) # reshape back in a 1D array

Comments

0

You can do:

import numpy as np
arr = np.array([8,7,6,5,4,3,2,1])
result = np.vstack((arr[1::2], arr[::2])).T.flatten()

output:
array([7, 8, 5, 6, 3, 4, 1, 2])

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.