misaki646's blog

By misaki646, history, 2 hours ago, In English

Today I find that python swap value hack doesn't work as intended all the time. Maybe the best practice is just write code line by line instead of this? If can someone please explain to me is there anything wrong?

Intention: Swap a and b

Python: a, b = b, a (usually works all the time and I actually use this in today div3C)

Expected: b, a = a, b works the same as above

But this time it doesn't work as intended

    for _ in range(int(input())):
        n = int(input())
        a = list(map(int, input().split()))
        a = [x-1 for x in a]
        res = 0
        for i in range(n):
            if a[i]>=0:
                mlen = 0
                ix = i
                while a[ix]>=0:
                    a[ix], ix = -1, a[ix]
                    #ix, a[ix] = a[ix], -1 # doesn't work the same as above
                    mlen+=1
                res += (mlen-1)//2
        print(res)
  • Vote: I like it
  • +4
  • Vote: I do not like it

»
2 hours ago, # |
  Vote: I like it 0 Vote: I do not like it

nvm I figured, Python will execute the right hand side first then the left hand side, ix will affect a[ix] but not the other way around since value of a[ix] is already stored.

But a[ix] will use the new value of ix since the order is from left to right which will break the code intention

  • »
    »
    2 hours ago, # ^ |
      Vote: I like it +5 Vote: I do not like it

    Idea from this