0

Within a numpy array of 48 elements, I have a series of swaps that I need to make.

34 -> 21 -> 42 -> 26 -> 34
36 -> 19 -> 44 -> 28 -> 36
39 -> 16 -> 47 -> 31 -> 39

where x -> y means the element at index x must go to the yth index. I'm trying to think of an efficient way to do this since the numbers are quite random and this is just one of the series of swaps that I need to make.

For example: Given the following array

original = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

I want to make the following swaps

1 -> 4 -> 6 -> 1

so I end up with

swapped = ['a', 'g', 'c', 'd', 'b', 'f', 'e', 'h']

so the 1st index element went to the 4th index, the 4th to the 6th, and the 6th to the 1st.

4
  • Are these numpy arrays? Or lists? Commented Nov 4, 2020 at 16:25
  • @nullUser These are numpy arrays. I'll edit the question Commented Nov 4, 2020 at 16:27
  • What format will your swap indices be in? Will they be hardcoded or dynamic? Commented Nov 4, 2020 at 16:44
  • @ThisIsAQuestion The indices are hardcoded Commented Nov 4, 2020 at 16:58

2 Answers 2

2

This is probably the most efficient way to perform a single of those sequences:

swaps = [34, 21, 42, 26, 34]
arr = np.arange(48)

from_idx = lst[:-1]
to_idx = lst[1:]
arr[to_idx] = arr[from_idx]
Sign up to request clarification or add additional context in comments.

Comments

0

Perhaps something like this.

def swap(input, index):
    start_index = index[0]
    for next_index in range(1, len(index)):
       input[start_index], input[next_index] = input[next_index] , input[start_index]
    
    return(input)

if __name__ == '__main__':
    input = ['A', 'B', 'C', 'D', 'E', 'F', 'G']
    index = [2,3,6,2]

    output = swap(input, index)
    print(output)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.