<jupyter_start><jupyter_text>[XOR swap - a beautiful trick](https://en.wikipedia.org/wiki/XOR_swap_algorithm)<jupyter_code>import numpy as np<jupyter_output><empty_output><jupyter_text>Swap 2 integers<jupyter_code>a = 123
b = 67
print(a, b)

a ^= b
b ^= a
a ^= b
print(a, b)<jupyter_output>123 67
67 123<jupyter_text>Swap 2 booleans<jupyter_code>a = True
b = False
print(a, b)

a ^= b
b ^= a
a ^= b
print(a, b)<jupyter_output>True False
False True<jupyter_text>Swap 2 numpy arrays<jupyter_code>a = np.array([[3, 5, 7], [9, 14, 21]])
b = np.array([[42, 8, 13], [18, 99, 453]])
print('a\n', a)
print('b\n', b)
print()

a ^= b
b ^= a
a ^= b
print('a\n', a)
print('b\n', b)<jupyter_output>a
 [[ 3  5  7]
 [ 9 14 21]]
b
 [[ 42   8  13]
 [ 18  99 453]]

a
 [[ 42   8  13]
 [ 18  99 453]]
b
 [[ 3  5  7]
 [ 9 14 21]]<jupyter_text>Swap 2 numpy arrays for a given list of indices<jupyter_code>a = np.array([[3, 5, 7], [9, 14, 21], [5, 55, 555]])
b = np.array([[42, 8, 13], [18, 99, 453], [6, 66, 666]])
rows = [0, 2]
print('a\n', a)
print('b\n', b)
print()

a[rows, :] ^= b[rows, :]
b[rows, :] ^= a[rows, :]
a[rows, :] ^= b[rows, :]
print('a\n', a)
print('b\n', b)<jupyter_output>a
 [[  3   5   7]
 [  9  14  21]
 [  5  55 555]]
b
 [[ 42   8  13]
 [ 18  99 453]
 [  6  66 666]]

a
 [[ 42   8  13]
 [  9  14  21]
 [  6  66 666]]
b
 [[  3   5   7]
 [ 18  99 453]
 [  5  55 555]]<jupyter_text>XOR swap function<jupyter_code>def xor_swap(a, b, rows=None):
    a[rows] ^= b[rows]
    b[rows] ^= a[rows]
    a[rows] ^= b[rows] 
a = np.array([5, 6])
b = np.array([9, 8])

print(a)
print(b)

print('xor_swap')
xor_swap(a, b)

print(a)
print(b)
a = np.array([[5, 6], [7, 8]])
b = np.array([[1, 2], [3, 4]])

print('a:\n', a)
print('b:\n', b)

print('\nxor_swap')
xor_swap(a, b, rows=[1])

print('a:\n', a)
print('b:\n', b)
a = np.array([[[5], [6]], [[7], [8]]])
b = np.array([[[1], [2]], [[3], [4]]])

print(a.shape)
print('a:\n', a)
print('b:\n', b)

print('\nxor_swap')
xor_swap(a, b)

print('a:\n', a)
print('b:\n', b)<jupyter_output>(2, 2, 1)
a:
 [[[5]
  [6]]

 [[7]
  [8]]]
b:
 [[[1]
  [2]]

 [[3]
  [4]]]

xor_swap
a:
 [[[1]
  [2]]

 [[3]
  [4]]]
b:
 [[[5]
  [6]]

 [[7]
  [8]]]
{'fraction_non_alphanumeric': 0.2594644506001847, 'fraction_numerical': 0.10018467220683287, 'mean_word_length': 3.404471544715447, 'pattern_counts': {'":': 0, '<': 20, '<?xml version=': 0, '>': 20, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '6', 'dir': 'jupyter-structured-clean-dedup', 'id': '587600', 'license': 'MIT', 'n_tokens_mistral': 1273, 'n_tokens_neox': 1127, 'n_words': 278, 'path': '2018-2019/assignment 5 (RBM)/misc/XOR_swap.ipynb', 'repo_name': 'Tudor67/Neural-Networks-Assignments', 'size': '2166'}