Moving Elements in Python Iteratively

I'm having trouble understanding what is going on behind the scenes for this simple piece of code:

def changeArray(arr): for i in range(len(arr)): arr[i], arr[arr[i] - 1] = arr[arr[i] - 1], arr[i] print(arr) return(arr) 

The code assumes that the array has integers from 1 to n as its elements. The output for this code when the input [1,3,4,2] is:

 [1, 3, 4, 2] [1, 4, 4, 3] [1, 4, 4, 3] [1, 4, 4, 3] Out[8]: [1, 4, 4, 3] 

while I expected it to print and return this:

 [1, 3, 4, 2] [1, 4, 3, 2] [1, 4, 3, 2] [1, 2, 3, 4] Out[8]: [1, 2, 3, 4] 

Why do values โ€‹โ€‹change at all when the code is just a replacement for elements?


Edit:

It turns out that swapping the swap order fixes the problem:

 def changeArray(arr): for i in range(len(arr)): arr[arr[i]-1], arr[i] = arr[i], arr[arr[i]-1] print(arr) return(arr) 

This gives the following result:

 [1, 3, 4, 2] [1, 4, 3, 2] [1, 4, 3, 2] [1, 2, 3, 4] Out[8]: [1, 2, 3, 4] 

How did the reordering change, as expected, and vice versa did something else?

+5
source share
2 answers

In general, you should not use the object you mutate to indicate the target positions that you want to replace, or it becomes very confusing.

When you write this:

  arr[i], arr[arr[i] - 1] = arr[arr[i] - 1], arr[i] 

This is roughly equivalent to:

 tup = arr[arr[i] - 1], arr[i] x, y = tup arr.__setitem__(i, x) arr.__setitem__(arr[i] - 1, y) 

(Full details on how to do this are in the reference documents , but hopefully an indestructible idea is much simpler.)

What should make it clear why you get the results. And also why all of the following do what you want:

 x = arr[i] - 1 arr[i], arr[x] = arr[x], arr[i] arr[arr[i] - 1], arr[i] = arr[i], arr[arr[i] - 1] def swap(x, y): arr[x], arr[y] = arr[y], arr[x] swap(i, arr[i] - 1) 

I think the first one is the easiest (the second one looks simple, but only misleading).

+3
source

Change expression to

  arr[arr[i] - 1], arr[i] = arr[i], arr[arr[i] - 1] 

works for me. Still do not know how and why the values โ€‹โ€‹have changed. I am new to python and also sorry.

0
source

Source: https://habr.com/ru/post/1276062/


All Articles