Python list in-place exchange nums[i], nums[nums[i]] = nums[nums[i]], nums[i] solution

Problem Description

Python list in-place exchange problem, when the index is in 数组[索引]the expression form , inappropriate exchange operation will lead to wrong output

  1. Method 1 (wrong)
nums[i], nums[nums[i]] = nums[nums[i]], nums[i]
  1. Method 2 (Correct)
nums[nums[i]], nums[i] = nums[i], nums[nums[i]]

test

# 法1
nums1 = [3,3,2,2,1,1]
i = 0
nums1[i], nums1[nums1[i]] = nums1[nums1[i]], nums1[i]
print(nums1)

# 法2
nums2 = [3,3,2,2,1,1]
i = 0
nums2[nums2[i]], nums2[i] = nums2[i], nums2[nums2[i]]
print(nums2)
执行完成,耗时:44 ms
[2, 3, 3, 2, 1, 1]
[2, 3, 2, 3, 1, 1]

reason

During execution , the left and right will be formed into tuplesnums1[i], nums1[nums1[i]] = nums1[nums1[i]], nums1[i] in python , and then assigned according to the principle of first left and then right . Therefore, it is advisable to set ( a , b ) = ( c , d ) (a, b) = (c, d)(a,b)=(c,d ) , the process isa = c , b = da = c, b = da=c,b=d , so herenums 1 [ i ] = nums 1 [ nums 1 [ i ] ] nums1[i] = nums1[nums1[i]]nums1[i]=When n u m s 1 [ n u m s 1 [ i ] ] , nums [ i ] nums[i]has been changedThe value of n u m s [ i ] , thennums 1 [ nums 1 [ i ] ] = nums 1 [ i ] nums1[nums1[i]] = nums1[i]nums1[nums1[i]]=When n u m s 1 [ i ] , the index on the left side of the equation changes, so an error occurs.

Specifically, i = 0 i = 0i=0 , first executenums 1 [ 0 ] = nums 1 [ nums 1 [ 0 ] ] nums1[0] = nums1[nums1[0]]nums1[0]=n u m s 1 [ n u m s 1 [ 0 ] ] , so
nums 1 [ nums 1 [ 0 ] ] = nums 1 [ 3 ] = 2 nums1[nums1[0]] = nums1[3] = 2nums1[nums1[0]]=nums1[3]=2 n u m s 1 [ 0 ] = 2 nums1[0] = 2 nums1[0]=2
Execute againnums 1 [ nums 1 [ 0 ] ] = nums 1 [ 0 ] nums1[nums1[0]] = nums1[0]nums1[nums1[0]]=When n u m s 1 [ 0 ] , the right side of the equation is calculated first, and then the value is copied to the left side, as follows:
nums 1 [ 0 ] = 2 nums1[0] = 2nums1[0]=2 n u m s 1 [ n u m s 1 [ 0 ] ] = n u m s 1 [ 2 ] = 2 nums1[nums1[0]] = nums1[2] = 2 nums1[nums1[0]]=nums1[2]=2

Therefore, the value modified in the second step nums1[2]is not modified, and nums1[3]the result is[2, 3, 3, 2, 1, 1]

think

For the correct way, no detailed analysis here

Guess you like

Origin blog.csdn.net/qq_45510888/article/details/123440823