Python Expressive Puzzlers 7: Swap

若您覺得文章寫得不錯,請點選文章上的廣告,來支持小編,謝謝。

底下兩個Java Class分別會輸出什麼結果?
1
2
3
4
5
6
7
8
public class CleverSwapOne {
  public static void main(String[] args) {
    int x = 1984;
    int y = 2001;
    x ^= y ^= x ^= y;
    System.out.println("x = " + x + "; y = " + y);
}
}

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
public class CleverSwapTwo {
  public static void main(String[] args) {
    int x = 1984;
    int y = 2001;
    x ^= y;
    y ^= x;
    x ^= y;
    System.out.println("x = " + x + "; y = " + y);
  }
}
CleverSwapOne會輸出x = 0; y = 1984,而CleverSwapTwo會輸出x = 2001; y = 1984。為什麼會這樣子呢?

根據JLS 15.7 的說明:「Evaluate Left-Hand Operand First」也就是CleverSwapOne 的執行順序如下:
1
2
3
4
5
6
7
// The actual behavior of x ^= y ^= x ^= y in Java
int tmp1 = x; // First appearance of x in the expression
int tmp2 = y; // First appearance of y
int tmp3 = x ^ y; // Compute x ^ y
x = tmp3; // Last assignment: Store x ^ y in x
y = tmp2 ^ tmp3; // 2nd assignment: Store original x value in y
x = tmp1 ^ y; // First assignment: Store 0 in x

如同原作所說:「 Do not assign to the same variable more than once in a single expression.」

那Python呢?
1
2
3
4
5
6
7
8
9
x = 1984
y = 2001

x ^= y
y ^= x
x ^= y

x ^= y ^= x ^= y
print('x = ', x, 'y = ',  y)

沒有留言: