该语法是交换变量的标准方法。但是,在处理被修改然后在交换的后续存储元素中使用的元素时,我们需要注意顺序。
使用带有直接索引的数组很好。例如:
def swap_indexes(A, i1, i2):
A[i1], A[i2] = A[i2], A[i1]
print('A[i1]=', A[i1], 'A[i2]=', A[i2])
return A
A = [0, 1, 2, 3, 4]
print('For A=', A)
print('swap indexes 1, 3:', swap_indexes(A, 1, 3))
给我们:
('对于 A=', [0, 1, 2, 3, 4])
('A[i1]=', 3, 'A[i2]=', 1)
('交换索引 1, 3:', [0, 3, 2, 1, 4])
但是,如果我们更改左侧第一个元素并在左侧第二个元素中使用它作为索引,这会导致交换错误。
def good_swap(P, i2):
j = P[i2]
#Below is correct, because P[i2] is modified after it is used in P[P[i2]]
print('Before: P[i2]=', P[i2], 'P[P[i2]]=', P[j])
P[P[i2]], P[i2] = P[i2], P[P[i2]]
print('Good swap: After P[i2]=', P[i2], 'P[P[i2]]=', P[j])
return P
def bad_swap(P, i2):
j = P[i2]
#Below is wrong, because P[i2] is modified and then used in P[P[i2]]
print('Before: P[i2]=', P[i2], 'P[P[i2]]=', P[j])
P[i2], P[P[i2]] = P[P[i2]], P[i2]
print('Bad swap: After P[i2]=', P[i2], 'P[P[i2]]=', P[j])
return P
P = [1, 2, 3, 4, 5]
print('For P=', P)
print('good swap with index 2:', good_swap(P, 2))
print('------')
P = [1, 2, 3, 4, 5]
print('bad swap with index 2:', bad_swap(P, 2))
('对于 P=', [1, 2, 3, 4, 5])
('之前:P[i2]=', 3, 'P[P[i2]]=', 4)
('好的交换:P[i2]='之后,4,'P[P[i2]]=',3)
('与索引 2 的良好交换:', [1, 2, 4, 3, 5])
('之前:P[i2]=', 3, 'P[P[i2]]=', 4)
('Bad swap: After P[i2]=', 4, 'P[P[i2]]=', 4)
('bad swap with index 2:', [1, 2, 4, 4, 3])
坏交换是不正确的,因为 P[i2] 是 3,我们期望 P[P[i2]] 是 P[3]。但是P[i2]先变成了4,所以后面的P[P[i2]]变成了P[4],覆盖的是第4个元素而不是第3个元素。
上述场景用于排列。更简单的好交换和坏交换是:
#good swap:
P[j], j = j, P[j]
#bad swap:
j, P[j] = P[j], j