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))
('For p =', [1,2,3,4,5])
('前:P[i2]=', 3, 'P[P[i2]]=', 4)
(“好交换:P (i2) = ', 4,“P [P (i2)] = ', 3)
('good swap with index 2:', [1,2,4,3,5])
('前:p [i2]=', 3, ' p [p [i2]]=', 4)
(“坏掉期:P (i2) = ', 4,“P [P (i2)] = ', 4)
('bad swap with index 2:', [1,2,4,4,3])