EPI Python 5.10 - python swap?

#1

I have a question about python swap like a, b = b, a.

Actually, the following is the solution code of EPI Python 5.10: apply_permutation.py

def apply_permutation(perm: List[int], A: List[int]) -> None:
    for i in range(len(A)):
        while perm[i] != i:
            A[perm[i]], A[i] = A[i], A[perm[i]]
            perm[perm[i]], perm[i] = perm[i], perm[perm[i]]

But, at the first time, I wrote the last line like this, (the order is different)
perm[i], perm[perm[i]] = perm[perm[i]], perm[i]

then, the result was different !

Can anyone tell me why ?
I tried to find solution in internet but, I even don’t know the key word for this issue.

Thank you.

0 Likes

#2

Two rules:

  1. Python is reading code left to right.
  2. If there is an assignment (like the = operator) Python evaluates the right side first.

Because Python is reading code left to right the problem in your solution is following:
the value of perm[i] is changed first. Instead of calling it perm[i] lets call it new_index then you change perm[new_index] and not at perm[perm[i]]

Compare that with their solution you will notice that they change always at perm[perm[i]], because it is written first.

0 Likes