Блог пользователя misaki646

Автор misaki646, история, 4 часа назад, По-английски

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)
  • Проголосовать: нравится
  • +5
  • Проголосовать: не нравится

»
4 часа назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

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

  • »
    »
    4 часа назад, # ^ |
      Проголосовать: нравится +6 Проголосовать: не нравится

    Idea from this