Блог пользователя 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)

Полный текст и комментарии »

  • Проголосовать: нравится
  • +13
  • Проголосовать: не нравится