diff --git a/Week 2/my_week2_solutions.ipynb b/Week 2/my_week2_solutions.ipynb new file mode 100644 index 0000000..26bca84 --- /dev/null +++ b/Week 2/my_week2_solutions.ipynb @@ -0,0 +1,3744 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# 100 numpy exercises\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 1. Import the numpy package under the name `np` (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": {}, + "outputs": [], + "source": [ + "import numpy as np" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 2. Print the numpy version and the configuration (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1.18.5\n", + "\n" + ] + } + ], + "source": [ + "print(np.__version__)\n", + "print(np.show_config)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 3. Create a null vector of size 10 (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n" + ] + } + ], + "source": [ + "null_vec = np.zeros(10)\n", + "print(null_vec)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 4. How to find the memory size of any array (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "8\n" + ] + } + ], + "source": [ + "a = np.array([1, 2])\n", + "print(a.size*a.itemsize)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 5. How to get the documentation of the numpy add function from the command line? (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "add(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj])\n", + "\n", + "Add arguments element-wise.\n", + "\n", + "Parameters\n", + "----------\n", + "x1, x2 : array_like\n", + " The arrays to be added. If ``x1.shape != x2.shape``, they must be broadcastable to a common shape (which becomes the shape of the output).\n", + "out : ndarray, None, or tuple of ndarray and None, optional\n", + " A location into which the result is stored. If provided, it must have\n", + " a shape that the inputs broadcast to. If not provided or None,\n", + " a freshly-allocated array is returned. A tuple (possible only as a\n", + " keyword argument) must have length equal to the number of outputs.\n", + "where : array_like, optional\n", + " This condition is broadcast over the input. At locations where the\n", + " condition is True, the `out` array will be set to the ufunc result.\n", + " Elsewhere, the `out` array will retain its original value.\n", + " Note that if an uninitialized `out` array is created via the default\n", + " ``out=None``, locations within it where the condition is False will\n", + " remain uninitialized.\n", + "**kwargs\n", + " For other keyword-only arguments, see the\n", + " :ref:`ufunc docs `.\n", + "\n", + "Returns\n", + "-------\n", + "add : ndarray or scalar\n", + " The sum of `x1` and `x2`, element-wise.\n", + " This is a scalar if both `x1` and `x2` are scalars.\n", + "\n", + "Notes\n", + "-----\n", + "Equivalent to `x1` + `x2` in terms of array broadcasting.\n", + "\n", + "Examples\n", + "--------\n", + ">>> np.add(1.0, 4.0)\n", + "5.0\n", + ">>> x1 = np.arange(9.0).reshape((3, 3))\n", + ">>> x2 = np.arange(3.0)\n", + ">>> np.add(x1, x2)\n", + "array([[ 0., 2., 4.],\n", + " [ 3., 5., 7.],\n", + " [ 6., 8., 10.]])\n" + ] + } + ], + "source": [ + "np.info(np.add)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 6. Create a null vector of size 10 but the fifth value which is 1 (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[0. 0. 0. 0. 1. 0. 0. 0. 0. 0.]\n" + ] + } + ], + "source": [ + "null_vec[4] = 1\n", + "print(null_vec)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 7. Create a vector with values ranging from 10 to 49 (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33\n", + " 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49]\n" + ] + } + ], + "source": [ + "a = np.arange(10,50)\n", + "print(a)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 8. Reverse a vector (first element becomes last) (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 28, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26\n", + " 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10]\n" + ] + } + ], + "source": [ + "print(a[::-1])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 9. Create a 3x3 matrix with values ranging from 0 to 8 (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 29, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[0 1 2]\n", + " [3 4 5]\n", + " [6 7 8]]\n" + ] + } + ], + "source": [ + "a = np.arange(9).reshape(3,3)\n", + "print(a)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 10. Find indices of non-zero elements from [1,2,0,0,4,0] (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 30, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "(array([0, 1, 4], dtype=int64),)\n" + ] + } + ], + "source": [ + "a = np.nonzero([1,2,0,0,4,0])\n", + "print(a)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 11. Create a 3x3 identity matrix (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "array([[1., 0., 0.],\n", + " [0., 1., 0.],\n", + " [0., 0., 1.]])" + ] + }, + "execution_count": 31, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "np.eye(3)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 12. Create a 3x3x3 array with random values (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "array([[[0.6917253 , 0.43425717, 0.6226793 ],\n", + " [0.89725237, 0.23453348, 0.73632391],\n", + " [0.23334608, 0.54134735, 0.47988204]],\n", + "\n", + " [[0.47093738, 0.85934496, 0.32995811],\n", + " [0.75329873, 0.05505369, 0.38274875],\n", + " [0.46357558, 0.1990875 , 0.53095164]],\n", + "\n", + " [[0.04162073, 0.05661598, 0.00754189],\n", + " [0.84508543, 0.12255054, 0.88461526],\n", + " [0.43778057, 0.67938669, 0.46440985]]])" + ] + }, + "execution_count": 32, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "np.random.random((3,3,3))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 13. Create a 10x10 array with random values and find the minimum and maximum values (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 34, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "0.012592810559576173 0.991096244217514\n" + ] + } + ], + "source": [ + "a = np.random.random((10,10))\n", + "print(np.min(a),np.max(a))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 14. Create a random vector of size 30 and find the mean value (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 35, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "0.5300021408858705" + ] + }, + "execution_count": 35, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "np.random.random(30).mean()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 15. Create a 2d array with 1 on the border and 0 inside (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 42, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[1. 1. 1. 1. 1.]\n", + " [1. 0. 0. 0. 1.]\n", + " [1. 0. 0. 0. 1.]\n", + " [1. 0. 0. 0. 1.]\n", + " [1. 1. 1. 1. 1.]]\n" + ] + } + ], + "source": [ + "a = np.ones((5,5))\n", + "a[1:-1,1:-1] = 0\n", + "print(a)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 16. How to add a border (filled with 0's) around an existing array? (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 46, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[0. 0. 0. 0. 0. 0. 0.]\n", + " [0. 1. 1. 1. 1. 1. 0.]\n", + " [0. 1. 1. 1. 1. 1. 0.]\n", + " [0. 1. 1. 1. 1. 1. 0.]\n", + " [0. 1. 1. 1. 1. 1. 0.]\n", + " [0. 1. 1. 1. 1. 1. 0.]\n", + " [0. 0. 0. 0. 0. 0. 0.]]\n" + ] + } + ], + "source": [ + "a = np.ones((5,5))\n", + "a = np.pad(a, pad_width=1, mode='constant', constant_values=0)\n", + "print(a)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 17. What is the result of the following expression? (???)\n", + "```python\n", + "0 * np.nan\n", + "np.nan == np.nan\n", + "np.inf > np.nan\n", + "np.nan - np.nan\n", + "np.nan in set([np.nan])\n", + "0.3 == 3 * 0.1\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 47, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "nan\n", + "False\n", + "False\n", + "nan\n", + "True\n", + "False\n" + ] + } + ], + "source": [ + "print(0 * np.nan)\n", + "print(np.nan == np.nan)\n", + "print(np.inf > np.nan)\n", + "print(np.nan - np.nan)\n", + "print(np.nan in set([np.nan]))\n", + "print(0.3 == 3 * 0.1)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 18. Create a 5x5 matrix with values 1,2,3,4 just below the diagonal (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 48, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "array([[0, 0, 0, 0, 0],\n", + " [1, 0, 0, 0, 0],\n", + " [0, 2, 0, 0, 0],\n", + " [0, 0, 3, 0, 0],\n", + " [0, 0, 0, 4, 0]])" + ] + }, + "execution_count": 48, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "np.diag(1+np.arange(4),k=-1)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 19. Create a 8x8 matrix and fill it with a checkerboard pattern (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 57, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[0. 1. 0. 1. 0. 1. 0. 1.]\n", + " [1. 0. 1. 0. 1. 0. 1. 0.]\n", + " [0. 1. 0. 1. 0. 1. 0. 1.]\n", + " [1. 0. 1. 0. 1. 0. 1. 0.]\n", + " [0. 1. 0. 1. 0. 1. 0. 1.]\n", + " [1. 0. 1. 0. 1. 0. 1. 0.]\n", + " [0. 1. 0. 1. 0. 1. 0. 1.]\n", + " [1. 0. 1. 0. 1. 0. 1. 0.]]\n" + ] + } + ], + "source": [ + "a = np.zeros((8,8))\n", + "a[1::2,::2] = 1\n", + "a[::2,1::2] = 1\n", + "print(a)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 20. Consider a (6,7,8) shape array, what is the index (x,y,z) of the 100th element?" + ] + }, + { + "cell_type": "code", + "execution_count": 58, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "(1, 5, 3)" + ] + }, + "execution_count": 58, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "np.unravel_index(99,(6,7,8))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 21. Create a checkerboard 8x8 matrix using the tile function (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 59, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "array([[0, 1, 0, 1, 0, 1, 0, 1],\n", + " [1, 0, 1, 0, 1, 0, 1, 0],\n", + " [0, 1, 0, 1, 0, 1, 0, 1],\n", + " [1, 0, 1, 0, 1, 0, 1, 0],\n", + " [0, 1, 0, 1, 0, 1, 0, 1],\n", + " [1, 0, 1, 0, 1, 0, 1, 0],\n", + " [0, 1, 0, 1, 0, 1, 0, 1],\n", + " [1, 0, 1, 0, 1, 0, 1, 0]])" + ] + }, + "execution_count": 59, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "np.tile( np.array([[0,1],[1,0]]), (4,4))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 22. Normalize a 5x5 random matrix (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 60, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[ 1.11177608 0.75774466 -1.32744122 0.39953331 -0.84582864]\n", + " [ 1.07025439 -0.03335812 1.28336295 0.61506915 1.12630766]\n", + " [ 0.97038375 -1.15357441 -0.55326851 -0.92900873 0.09150767]\n", + " [ 1.29251021 -0.33180858 -0.62425593 -1.70940067 1.09070013]\n", + " [-1.61290363 -0.42947804 1.45666645 -0.83583964 -0.8796503 ]]\n" + ] + } + ], + "source": [ + "a = np.random.random((5,5))\n", + "a = (a - np.mean (a)) / (np.std (a))\n", + "print(a)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 23. Create a custom dtype that describes a color as four unsigned bytes (RGBA) (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 63, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + ":1: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " a = np.dtype([(\"r\", np.ubyte, 1),\n" + ] + } + ], + "source": [ + "a = np.dtype([(\"r\", np.ubyte, 1),\n", + " (\"g\", np.ubyte, 1),\n", + " (\"b\", np.ubyte, 1),\n", + " (\"a\", np.ubyte, 1)])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 24. Multiply a 5x3 matrix by a 3x2 matrix (real matrix product) (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 65, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "array([[3., 3.],\n", + " [3., 3.],\n", + " [3., 3.],\n", + " [3., 3.],\n", + " [3., 3.]])" + ] + }, + "execution_count": 65, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "np.dot(np.ones((5,3)), np.ones((3,2)))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 25. Given a 1D array, negate all elements which are between 3 and 8, in place. (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 66, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[ 0 1 2 3 -4 -5 -6 -7 8 9 10]\n" + ] + } + ], + "source": [ + "a = np.arange(11)\n", + "a[(3 < a) & (a < 8)] *= -1\n", + "print(a)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 26. What is the output of the following script? (???)\n", + "```python\n", + "print(sum(range(5),-1))\n", + "from numpy import *\n", + "print(sum(range(5),-1))\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 71, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "10\n", + "10\n" + ] + } + ], + "source": [ + "print(sum(range(5),-1))\n", + "from numpy import *\n", + "print(sum(range(5),-1))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 27. Consider an integer vector Z, which of these expressions are legal? (???)\n", + "```python\n", + "Z**Z\n", + "2 << Z >> 2\n", + "Z <- Z\n", + "1j*Z\n", + "Z/1/1\n", + "ZZ\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 82, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1j*Z\n" + ] + } + ], + "source": [ + "print(\"1j*Z\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 28. What are the result of the following expressions?\n", + "```python\n", + "np.array(0) / np.array(0)\n", + "np.array(0) // np.array(0)\n", + "np.array([np.nan]).astype(int).astype(float)\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 83, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "nan\n", + "0\n", + "[-2.14748365e+09]\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + ":1: RuntimeWarning: invalid value encountered in true_divide\n", + " print(np.array(0) / np.array(0))\n", + ":2: RuntimeWarning: divide by zero encountered in floor_divide\n", + " print(np.array(0) // np.array(0))\n" + ] + } + ], + "source": [ + "print(np.array(0) / np.array(0))\n", + "print(np.array(0) // np.array(0))\n", + "print(np.array([np.nan]).astype(int).astype(float))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 29. How to round away from zero a float array ? (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 84, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "array([ 0., 1., 2., 3., -4., -5., -6., -7., 8., 9., 10.])" + ] + }, + "execution_count": 84, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "np.where(a>0, np.ceil(a), np.floor(a))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 30. How to find common values between two arrays? (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 92, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[1 2 6]\n" + ] + } + ], + "source": [ + "a = np.random.randint(0,10,10)\n", + "b = np.random.randint(0,10,10)\n", + "print(np.intersect1d(a,b))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 31. How to ignore all numpy warnings (not recommended)? (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 95, + "metadata": {}, + "outputs": [], + "source": [ + "None" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 32. Is the following expressions true? (???)\n", + "```python\n", + "np.sqrt(-1) == np.emath.sqrt(-1)\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 94, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + ":1: RuntimeWarning: invalid value encountered in sqrt\n", + " np.sqrt(-1) == np.emath.sqrt(-1)\n" + ] + }, + { + "data": { + "text/plain": [ + "False" + ] + }, + "execution_count": 94, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "np.sqrt(-1) == np.emath.sqrt(-1)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 33. How to get the dates of yesterday, today and tomorrow? (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 99, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "2021-01-30\n", + "2021-01-31\n", + "2021-02-01\n" + ] + } + ], + "source": [ + "print(np.datetime64('today') - np.timedelta64(1))\n", + "print(np.datetime64('today'))\n", + "print(np.datetime64('today') + np.timedelta64(1))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 34. How to get all the dates corresponding to the month of July 2016? (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 100, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "array(['2016-07-01', '2016-07-02', '2016-07-03', '2016-07-04',\n", + " '2016-07-05', '2016-07-06', '2016-07-07', '2016-07-08',\n", + " '2016-07-09', '2016-07-10', '2016-07-11', '2016-07-12',\n", + " '2016-07-13', '2016-07-14', '2016-07-15', '2016-07-16',\n", + " '2016-07-17', '2016-07-18', '2016-07-19', '2016-07-20',\n", + " '2016-07-21', '2016-07-22', '2016-07-23', '2016-07-24',\n", + " '2016-07-25', '2016-07-26', '2016-07-27', '2016-07-28',\n", + " '2016-07-29', '2016-07-30', '2016-07-31'], dtype='datetime64[D]')" + ] + }, + "execution_count": 100, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "np.arange('2016-07', '2016-08', dtype='datetime64[D]')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 35. How to compute ((A+B)*(-A/2)) in place (without copy)? (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 101, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "array([-1.5, -1.5, -1.5])" + ] + }, + "execution_count": 101, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "A = np.ones(3)*1\n", + "B = np.ones(3)*2\n", + "C = np.ones(3)*3\n", + "np.add(A,B,out=B)\n", + "np.divide(A,2,out=A)\n", + "np.negative(A,out=A)\n", + "np.multiply(A,B,out=A)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 36. Extract the integer part of a random array of positive numbers using 4 different methods (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 102, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[5. 4. 7. 0. 1. 8. 7. 3. 5. 2.]\n", + "[5. 4. 7. 0. 1. 8. 7. 3. 5. 2.]\n", + "[5. 4. 7. 0. 1. 8. 7. 3. 5. 2.]\n", + "[5 4 7 0 1 8 7 3 5 2]\n", + "[5. 4. 7. 0. 1. 8. 7. 3. 5. 2.]\n" + ] + } + ], + "source": [ + "Z = np.random.uniform(0,10,10)\n", + "\n", + "print(Z - Z%1)\n", + "print(Z // 1)\n", + "print(np.floor(Z))\n", + "print(Z.astype(int))\n", + "print(np.trunc(Z))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 37. Create a 5x5 matrix with row values ranging from 0 to 4 (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 103, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[0. 1. 2. 3. 4.]\n", + " [0. 1. 2. 3. 4.]\n", + " [0. 1. 2. 3. 4.]\n", + " [0. 1. 2. 3. 4.]\n", + " [0. 1. 2. 3. 4.]]\n" + ] + } + ], + "source": [ + "Z = np.zeros((5,5))\n", + "Z += np.arange(5)\n", + "print(Z)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 38. Consider a generator function that generates 10 integers and use it to build an array (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 104, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[0. 1. 2. 3. 4. 5. 6. 7. 8. 9.]\n" + ] + } + ], + "source": [ + "def generate():\n", + " for x in range(10):\n", + " yield x\n", + "Z = np.fromiter(generate(),dtype=float,count=-1)\n", + "print(Z)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 39. Create a vector of size 10 with values ranging from 0 to 1, both excluded (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 105, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "array([0.09090909, 0.18181818, 0.27272727, 0.36363636, 0.45454545,\n", + " 0.54545455, 0.63636364, 0.72727273, 0.81818182, 0.90909091])" + ] + }, + "execution_count": 105, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "np.linspace(0,1,11,endpoint=False)[1:]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 40. Create a random vector of size 10 and sort it (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 109, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[0.06828586 0.10660859 0.15933565 0.32088804 0.37283942 0.4021088\n", + " 0.42401573 0.73086386 0.91681459 0.91922321]\n" + ] + } + ], + "source": [ + "Z = np.random.random(10)\n", + "Z.sort()\n", + "print(Z)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 41. How to sum a small array faster than np.sum? (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 110, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "45" + ] + }, + "execution_count": 110, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "Z = np.arange(10)\n", + "np.add.reduce(Z)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 42. Consider two random array A and B, check if they are equal (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 111, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "False\n", + "False\n" + ] + } + ], + "source": [ + "A = np.random.randint(0,2,5)\n", + "B = np.random.randint(0,2,5)\n", + "equal = np.allclose(A,B)\n", + "print(equal)\n", + "equal = np.array_equal(A,B)\n", + "print(equal)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 43. Make an array immutable (read-only) (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 113, + "metadata": {}, + "outputs": [], + "source": [ + "None" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 44. Consider a random 10x2 matrix representing cartesian coordinates, convert them to polar coordinates (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 117, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[0.63270586 0.83069244 0.93746751 0.95705363 0.5058014 0.81495066\n", + " 0.72577865 0.78451294 0.69502919 0.80257417]\n", + "[0.03654107 1.5160234 0.58341916 0.26902709 0.24834597 0.31717087\n", + " 1.14711389 1.15929357 0.60938576 1.03164357]\n" + ] + } + ], + "source": [ + "Z = np.random.random((10,2))\n", + "X,Y = Z[:,0], Z[:,1]\n", + "R = np.sqrt(X**2+Y**2)\n", + "T = np.arctan2(Y,X)\n", + "print(R)\n", + "print(T)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 45. Create random vector of size 10 and replace the maximum value by 0 (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 118, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[0.45177217 0. 0.19131814 0.97222989 0.19690991 0.47487646\n", + " 0.05187143 0.6775869 0.44895324 0.25855037]\n" + ] + } + ], + "source": [ + "Z = np.random.random(10)\n", + "Z[Z.argmax()] = 0\n", + "print(Z)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 46. Create a structured array with `x` and `y` coordinates covering the [0,1]x[0,1] area (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 119, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[(0. , 0. ) (0.25, 0. ) (0.5 , 0. ) (0.75, 0. ) (1. , 0. )]\n", + " [(0. , 0.25) (0.25, 0.25) (0.5 , 0.25) (0.75, 0.25) (1. , 0.25)]\n", + " [(0. , 0.5 ) (0.25, 0.5 ) (0.5 , 0.5 ) (0.75, 0.5 ) (1. , 0.5 )]\n", + " [(0. , 0.75) (0.25, 0.75) (0.5 , 0.75) (0.75, 0.75) (1. , 0.75)]\n", + " [(0. , 1. ) (0.25, 1. ) (0.5 , 1. ) (0.75, 1. ) (1. , 1. )]]\n" + ] + } + ], + "source": [ + "Z = np.zeros((5,5), [('x',float),('y',float)])\n", + "Z['x'], Z['y'] = np.meshgrid(np.linspace(0,1,5),\n", + " np.linspace(0,1,5))\n", + "print(Z)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 47. Given two arrays, X and Y, construct the Cauchy matrix C (Cij =1/(xi - yj))" + ] + }, + { + "cell_type": "code", + "execution_count": 120, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "3638.1636371179666\n" + ] + } + ], + "source": [ + "X = np.arange(8)\n", + "Y = X + 0.5\n", + "C = 1.0 / np.subtract.outer(X, Y)\n", + "print(np.linalg.det(C))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 48. Print the minimum and maximum representable value for each numpy scalar type (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 121, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "-128\n", + "127\n", + "-2147483648\n", + "2147483647\n", + "-9223372036854775808\n", + "9223372036854775807\n", + "-3.4028235e+38\n", + "3.4028235e+38\n", + "1.1920929e-07\n", + "-1.7976931348623157e+308\n", + "1.7976931348623157e+308\n", + "2.220446049250313e-16\n" + ] + } + ], + "source": [ + "for dtype in [np.int8, np.int32, np.int64]:\n", + " print(np.iinfo(dtype).min)\n", + " print(np.iinfo(dtype).max)\n", + "for dtype in [np.float32, np.float64]:\n", + " print(np.finfo(dtype).min)\n", + " print(np.finfo(dtype).max)\n", + " print(np.finfo(dtype).eps)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 49. How to print all the values of an array? (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 122, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n", + " [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n", + " [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n", + " [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n", + " [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n", + " [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n", + " [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n", + " [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n", + " [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n", + " [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n", + " [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n", + " [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n", + " [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n", + " [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n", + " [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n", + " [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]\n" + ] + } + ], + "source": [ + "np.set_printoptions(threshold=float(\"inf\"))\n", + "Z = np.zeros((16,16))\n", + "print(Z)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 50. How to find the closest value (to a given scalar) in a vector? (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 123, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "85\n" + ] + } + ], + "source": [ + "Z = np.arange(100)\n", + "v = np.random.uniform(0,100)\n", + "index = (np.abs(Z-v)).argmin()\n", + "print(Z[index])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 51. Create a structured array representing a position (x,y) and a color (r,g,b) (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 124, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[((0., 0.), (0., 0., 0.)) ((0., 0.), (0., 0., 0.))\n", + " ((0., 0.), (0., 0., 0.)) ((0., 0.), (0., 0., 0.))\n", + " ((0., 0.), (0., 0., 0.)) ((0., 0.), (0., 0., 0.))\n", + " ((0., 0.), (0., 0., 0.)) ((0., 0.), (0., 0., 0.))\n", + " ((0., 0.), (0., 0., 0.)) ((0., 0.), (0., 0., 0.))]\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + ":1: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n", + " Z = np.zeros(10, [ ('position', [ ('x', float, 1),\n" + ] + } + ], + "source": [ + "Z = np.zeros(10, [ ('position', [ ('x', float, 1),\n", + " ('y', float, 1)]),\n", + " ('color', [ ('r', float, 1),\n", + " ('g', float, 1),\n", + " ('b', float, 1)])])\n", + "print(Z)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 52. Consider a random vector with shape (100,2) representing coordinates, find point by point distances (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 125, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[0. 0.83574036 0.76921779 0.55581706 0.36777161 0.60927588\n", + " 0.78070512 1.1884478 0.96366768 0.71330047]\n", + " [0.83574036 0. 0.39105595 0.38616767 0.76839878 0.86248832\n", + " 0.06301501 0.7637587 0.79146174 0.50056288]\n", + " [0.76921779 0.39105595 0. 0.22180615 0.53524334 0.53232244\n", + " 0.34399412 0.46393334 0.40459234 0.12699967]\n", + " [0.55581706 0.38616767 0.22180615 0. 0.38857468 0.48407889\n", + " 0.32348142 0.67787151 0.54900975 0.22089171]\n", + " [0.36777161 0.76839878 0.53524334 0.38857468 0. 0.24454666\n", + " 0.70542571 0.87660213 0.61607717 0.43577884]\n", + " [0.60927588 0.86248832 0.53232244 0.48407889 0.24454666 0.\n", + " 0.80147152 0.74177228 0.44122317 0.40675308]\n", + " [0.78070512 0.06301501 0.34399412 0.32348142 0.70542571 0.80147152\n", + " 0. 0.74224042 0.74781727 0.44721051]\n", + " [1.1884478 0.7637587 0.46393334 0.67787151 0.87660213 0.74177228\n", + " 0.74224042 0. 0.31522572 0.4777504 ]\n", + " [0.96366768 0.79146174 0.40459234 0.54900975 0.61607717 0.44122317\n", + " 0.74781727 0.31522572 0. 0.33050838]\n", + " [0.71330047 0.50056288 0.12699967 0.22089171 0.43577884 0.40675308\n", + " 0.44721051 0.4777504 0.33050838 0. ]]\n", + "[[0. 0.44031177 0.55490513 0.54726999 0.23061644 0.80231098\n", + " 0.73595886 0.10616505 0.62163886 0.11705605]\n", + " [0.44031177 0. 0.87430583 0.47500762 0.22991724 0.44391587\n", + " 0.49814052 0.39095278 0.64128069 0.45188732]\n", + " [0.55490513 0.87430583 0. 0.60239723 0.74551347 1.03368222\n", + " 0.85182233 0.52178 0.50547002 0.658334 ]\n", + " [0.54726999 0.47500762 0.60239723 0. 0.52915918 0.43901561\n", + " 0.2511987 0.44110637 0.17637711 0.6460264 ]\n", + " [0.23061644 0.22991724 0.74551347 0.52915918 0. 0.64946313\n", + " 0.6451426 0.22391495 0.65935184 0.22227352]\n", + " [0.80231098 0.44391587 1.03368222 0.43901561 0.64946313 0.\n", + " 0.22738661 0.71342798 0.59196332 0.85502458]\n", + " [0.73595886 0.49814052 0.85182233 0.2511987 0.6451426 0.22738661\n", + " 0. 0.63386728 0.37670283 0.81523574]\n", + " [0.10616505 0.39095278 0.52178 0.44110637 0.22391495 0.71342798\n", + " 0.63386728 0. 0.52042613 0.21238735]\n", + " [0.62163886 0.64128069 0.50547002 0.17637711 0.65935184 0.59196332\n", + " 0.37670283 0.52042613 0. 0.73280973]\n", + " [0.11705605 0.45188732 0.658334 0.6460264 0.22227352 0.85502458\n", + " 0.81523574 0.21238735 0.73280973 0. ]]\n" + ] + } + ], + "source": [ + "Z = np.random.random((10,2))\n", + "X,Y = np.atleast_2d(Z[:,0], Z[:,1])\n", + "D = np.sqrt( (X-X.T)**2 + (Y-Y.T)**2)\n", + "print(D)\n", + "\n", + "# Much faster with scipy\n", + "import scipy\n", + "# Thanks Gavin Heverly-Coulson (#issue 1)\n", + "import scipy.spatial\n", + "\n", + "Z = np.random.random((10,2))\n", + "D = scipy.spatial.distance.cdist(Z,Z)\n", + "print(D)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 53. How to convert a float (32 bits) array into an integer (32 bits) in place?" + ] + }, + { + "cell_type": "code", + "execution_count": 126, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[ 0 54 30 19 9 13 20 98 49 4]\n" + ] + } + ], + "source": [ + "Z = (np.random.rand(10)*100).astype(np.float32)\n", + "Y = Z.view(np.int32)\n", + "Y[:] = Z\n", + "print(Y)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 54. How to read the following file? (???)\n", + "```\n", + "1, 2, 3, 4, 5\n", + "6, , , 7, 8\n", + " , , 9,10,11\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 127, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[ 1 2 3 4 5]\n", + " [ 6 -1 -1 7 8]\n", + " [-1 -1 9 10 11]]\n" + ] + } + ], + "source": [ + "from io import StringIO\n", + "\n", + "# Fake file\n", + "s = StringIO('''1, 2, 3, 4, 5\n", + "\n", + " 6, , , 7, 8\n", + "\n", + " , , 9,10,11\n", + "''')\n", + "Z = np.genfromtxt(s, delimiter=\",\", dtype=np.int)\n", + "print(Z)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 55. What is the equivalent of enumerate for numpy arrays? (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 128, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "(0, 0) 0\n", + "(0, 1) 1\n", + "(0, 2) 2\n", + "(1, 0) 3\n", + "(1, 1) 4\n", + "(1, 2) 5\n", + "(2, 0) 6\n", + "(2, 1) 7\n", + "(2, 2) 8\n", + "(0, 0) 0\n", + "(0, 1) 1\n", + "(0, 2) 2\n", + "(1, 0) 3\n", + "(1, 1) 4\n", + "(1, 2) 5\n", + "(2, 0) 6\n", + "(2, 1) 7\n", + "(2, 2) 8\n" + ] + } + ], + "source": [ + "Z = np.arange(9).reshape(3,3)\n", + "for index, value in np.ndenumerate(Z):\n", + " print(index, value)\n", + "for index in np.ndindex(Z.shape):\n", + " print(index, Z[index])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 56. Generate a generic 2D Gaussian-like array (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 129, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[0.36787944 0.44822088 0.51979489 0.57375342 0.60279818 0.60279818\n", + " 0.57375342 0.51979489 0.44822088 0.36787944]\n", + " [0.44822088 0.54610814 0.63331324 0.69905581 0.73444367 0.73444367\n", + " 0.69905581 0.63331324 0.54610814 0.44822088]\n", + " [0.51979489 0.63331324 0.73444367 0.81068432 0.85172308 0.85172308\n", + " 0.81068432 0.73444367 0.63331324 0.51979489]\n", + " [0.57375342 0.69905581 0.81068432 0.89483932 0.9401382 0.9401382\n", + " 0.89483932 0.81068432 0.69905581 0.57375342]\n", + " [0.60279818 0.73444367 0.85172308 0.9401382 0.98773022 0.98773022\n", + " 0.9401382 0.85172308 0.73444367 0.60279818]\n", + " [0.60279818 0.73444367 0.85172308 0.9401382 0.98773022 0.98773022\n", + " 0.9401382 0.85172308 0.73444367 0.60279818]\n", + " [0.57375342 0.69905581 0.81068432 0.89483932 0.9401382 0.9401382\n", + " 0.89483932 0.81068432 0.69905581 0.57375342]\n", + " [0.51979489 0.63331324 0.73444367 0.81068432 0.85172308 0.85172308\n", + " 0.81068432 0.73444367 0.63331324 0.51979489]\n", + " [0.44822088 0.54610814 0.63331324 0.69905581 0.73444367 0.73444367\n", + " 0.69905581 0.63331324 0.54610814 0.44822088]\n", + " [0.36787944 0.44822088 0.51979489 0.57375342 0.60279818 0.60279818\n", + " 0.57375342 0.51979489 0.44822088 0.36787944]]\n" + ] + } + ], + "source": [ + "X, Y = np.meshgrid(np.linspace(-1,1,10), np.linspace(-1,1,10))\n", + "D = np.sqrt(X*X+Y*Y)\n", + "sigma, mu = 1.0, 0.0\n", + "G = np.exp(-( (D-mu)**2 / ( 2.0 * sigma**2 ) ) )\n", + "print(G)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 57. How to randomly place p elements in a 2D array? (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 130, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n", + " [0. 0. 0. 0. 0. 0. 1. 0. 0. 0.]\n", + " [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n", + " [0. 0. 0. 0. 0. 0. 0. 1. 0. 0.]\n", + " [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n", + " [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n", + " [0. 0. 0. 0. 0. 0. 0. 0. 1. 0.]\n", + " [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n", + " [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n", + " [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]\n" + ] + } + ], + "source": [ + "n = 10\n", + "p = 3\n", + "Z = np.zeros((n,n))\n", + "np.put(Z, np.random.choice(range(n*n), p, replace=False),1)\n", + "print(Z)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 58. Subtract the mean of each row of a matrix (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 131, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[ 0.25612054 0.22408246 -0.05431306 -0.21846373 -0.18665782 0.33371398\n", + " 0.39986657 -0.446151 0.18587729 -0.49407523]\n", + " [ 0.28063691 -0.15585652 -0.33185794 -0.51707518 0.11742492 0.30315107\n", + " 0.35395027 0.07729341 -0.23826767 0.11060073]\n", + " [ 0.19356638 0.20887254 0.08222117 0.2911826 0.21450999 -0.2071198\n", + " -0.2218728 -0.15347866 -0.28261734 -0.12526409]\n", + " [-0.37001543 0.14166302 -0.06690346 0.22301931 -0.25715988 0.07108671\n", + " 0.43519413 -0.36234559 -0.09602892 0.28149012]\n", + " [-0.04984484 -0.48398481 0.46889383 0.21377889 0.46534985 -0.47234487\n", + " -0.29175575 0.09166795 0.35067681 -0.29243705]]\n" + ] + } + ], + "source": [ + "X = np.random.rand(5, 10)\n", + "\n", + "# Recent versions of numpy\n", + "Y = X - X.mean(axis=1, keepdims=True)\n", + "\n", + "# Older versions of numpy\n", + "Y = X - X.mean(axis=1).reshape(-1, 1)\n", + "\n", + "print(Y)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 59. How to sort an array by the nth column? (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 132, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[7 0 4]\n", + " [5 9 4]\n", + " [2 4 1]]\n", + "[[7 0 4]\n", + " [2 4 1]\n", + " [5 9 4]]\n" + ] + } + ], + "source": [ + "Z = np.random.randint(0,10,(3,3))\n", + "print(Z)\n", + "print(Z[Z[:,1].argsort()])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 60. How to tell if a given 2D array has null columns? (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 133, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "True\n" + ] + } + ], + "source": [ + "Z = np.random.randint(0,3,(3,10))\n", + "print((~Z.any(axis=0)).any())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 61. Find the nearest value from a given value in an array (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 135, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "0.33266691749592736\n" + ] + } + ], + "source": [ + "Z = np.random.uniform(0,1,10)\n", + "z = 0.5\n", + "m = Z.flat[np.abs(Z - z).argmin()]\n", + "print(m)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 62. Considering two arrays with shape (1,3) and (3,1), how to compute their sum using an iterator? (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 136, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[0 1 2]\n", + " [1 2 3]\n", + " [2 3 4]]\n" + ] + } + ], + "source": [ + "A = np.arange(3).reshape(3,1)\n", + "B = np.arange(3).reshape(1,3)\n", + "it = np.nditer([A,B,None])\n", + "for x,y,z in it: z[...] = x + y\n", + "print(it.operands[2])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 63. Create an array class that has a name attribute (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 137, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "range_10\n" + ] + } + ], + "source": [ + "class NamedArray(np.ndarray):\n", + " def __new__(cls, array, name=\"no name\"):\n", + " obj = np.asarray(array).view(cls)\n", + " obj.name = name\n", + " return obj\n", + " def __array_finalize__(self, obj):\n", + " if obj is None: return\n", + " self.info = getattr(obj, 'name', \"no name\")\n", + "\n", + "Z = NamedArray(np.arange(10), \"range_10\")\n", + "print (Z.name)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 64. Consider a given vector, how to add 1 to each element indexed by a second vector (be careful with repeated indices)? (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 138, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[5. 3. 5. 1. 2. 3. 3. 5. 1. 2.]\n" + ] + } + ], + "source": [ + "Z = np.ones(10)\n", + "I = np.random.randint(0,len(Z),20)\n", + "Z += np.bincount(I, minlength=len(Z))\n", + "print(Z)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 65. How to accumulate elements of a vector (X) to an array (F) based on an index list (I)? (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 139, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[0. 7. 0. 6. 5. 0. 0. 0. 0. 3.]\n" + ] + } + ], + "source": [ + "X = [1,2,3,4,5,6]\n", + "I = [1,3,9,3,4,1]\n", + "F = np.bincount(I,X)\n", + "print(F)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 66. Considering a (w,h,3) image of (dtype=ubyte), compute the number of unique colors (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 140, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[0 1]\n" + ] + } + ], + "source": [ + "w,h = 16,16\n", + "I = np.random.randint(0,2,(h,w,3)).astype(np.ubyte)\n", + "F = I[...,0]*256*256 + I[...,1]*256 +I[...,2]\n", + "n = len(np.unique(F))\n", + "print(np.unique(I))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 67. Considering a four dimensions array, how to get sum over the last two axis at once? (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 141, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[54 50 75 56]\n", + " [50 64 60 38]\n", + " [52 28 49 68]]\n", + "[[54 50 75 56]\n", + " [50 64 60 38]\n", + " [52 28 49 68]]\n" + ] + } + ], + "source": [ + "A = np.random.randint(0,10,(3,4,3,4))\n", + "# solution by passing a tuple of axes (introduced in numpy 1.7.0)\n", + "sum = A.sum(axis=(-2,-1))\n", + "print(sum)\n", + "# solution by flattening the last two dimensions into one\n", + "# (useful for functions that don't accept tuples for axis argument)\n", + "sum = A.reshape(A.shape[:-2] + (-1,)).sum(axis=-1)\n", + "print(sum)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 68. Considering a one-dimensional vector D, how to compute means of subsets of D using a vector S of same size describing subset indices? (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 142, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[0.57794809 0.54437101 0.56752469 0.64208817 0.5435141 0.49192789\n", + " 0.5748291 0.44721468 0.3044052 0.65221174]\n" + ] + } + ], + "source": [ + "D = np.random.uniform(0,1,100)\n", + "S = np.random.randint(0,10,100)\n", + "D_sums = np.bincount(S, weights=D)\n", + "D_counts = np.bincount(S)\n", + "D_means = D_sums / D_counts\n", + "print(D_means)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 69. How to get the diagonal of a dot product? (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 143, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "array([1.59380327, 1.69083997, 1.86371607, 1.63294483, 1.81299861])" + ] + }, + "execution_count": 143, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "A = np.random.uniform(0,1,(5,5))\n", + "B = np.random.uniform(0,1,(5,5))\n", + "np.sum(A * B.T, axis=1)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 70. Consider the vector [1, 2, 3, 4, 5], how to build a new vector with 3 consecutive zeros interleaved between each value? (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 144, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[1. 0. 0. 0. 2. 0. 0. 0. 3. 0. 0. 0. 4. 0. 0. 0. 5.]\n" + ] + } + ], + "source": [ + "\n", + "Z = np.array([1,2,3,4,5])\n", + "nz = 3\n", + "Z0 = np.zeros(len(Z) + (len(Z)-1)*(nz))\n", + "Z0[::nz+1] = Z\n", + "print(Z0)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 71. Consider an array of dimension (5,5,3), how to mulitply it by an array with dimensions (5,5)? (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 145, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[[2. 2. 2.]\n", + " [2. 2. 2.]\n", + " [2. 2. 2.]\n", + " [2. 2. 2.]\n", + " [2. 2. 2.]]\n", + "\n", + " [[2. 2. 2.]\n", + " [2. 2. 2.]\n", + " [2. 2. 2.]\n", + " [2. 2. 2.]\n", + " [2. 2. 2.]]\n", + "\n", + " [[2. 2. 2.]\n", + " [2. 2. 2.]\n", + " [2. 2. 2.]\n", + " [2. 2. 2.]\n", + " [2. 2. 2.]]\n", + "\n", + " [[2. 2. 2.]\n", + " [2. 2. 2.]\n", + " [2. 2. 2.]\n", + " [2. 2. 2.]\n", + " [2. 2. 2.]]\n", + "\n", + " [[2. 2. 2.]\n", + " [2. 2. 2.]\n", + " [2. 2. 2.]\n", + " [2. 2. 2.]\n", + " [2. 2. 2.]]]\n" + ] + } + ], + "source": [ + "A = np.ones((5,5,3))\n", + "B = 2*np.ones((5,5))\n", + "print(A * B[:,:,None])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 72. How to swap two rows of an array? (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 146, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[ 5 6 7 8 9]\n", + " [ 0 1 2 3 4]\n", + " [10 11 12 13 14]\n", + " [15 16 17 18 19]\n", + " [20 21 22 23 24]]\n" + ] + } + ], + "source": [ + "A = np.arange(25).reshape(5,5)\n", + "A[[0,1]] = A[[1,0]]\n", + "print(A)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 73. Consider a set of 10 triplets describing 10 triangles (with shared vertices), find the set of unique line segments composing all the triangles (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 147, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[( 0, 21) ( 0, 58) ( 4, 10) ( 4, 47) (10, 47) (11, 13) (11, 69) (13, 69)\n", + " (15, 32) (15, 85) (20, 25) (20, 37) (21, 58) (23, 64) (23, 72) (25, 37)\n", + " (27, 91) (29, 36) (29, 48) (32, 85) (36, 48) (36, 58) (36, 79) (58, 79)\n", + " (64, 72) (71, 84) (71, 96) (84, 96) (91, 91)]\n" + ] + } + ], + "source": [ + "faces = np.random.randint(0,100,(10,3))\n", + "F = np.roll(faces.repeat(2,axis=1),-1,axis=1)\n", + "F = F.reshape(len(F)*3,2)\n", + "F = np.sort(F,axis=1)\n", + "G = F.view( dtype=[('p0',F.dtype),('p1',F.dtype)] )\n", + "G = np.unique(G)\n", + "print(G)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 74. Given a sorted array C that corresponds to a bincount, how to produce an array A such that np.bincount(A) == C? (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 148, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[1 1 2 3 4 4 6]\n" + ] + } + ], + "source": [ + "C = np.bincount([1,1,2,3,4,4,6])\n", + "A = np.repeat(np.arange(len(C)), C)\n", + "print(A)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 75. How to compute averages using a sliding window over an array? (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 149, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[ 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18.]\n" + ] + } + ], + "source": [ + "def moving_average(a, n=3) :\n", + " ret = np.cumsum(a, dtype=float)\n", + " ret[n:] = ret[n:] - ret[:-n]\n", + " return ret[n - 1:] / n\n", + "Z = np.arange(20)\n", + "print(moving_average(Z, n=3))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 76. Consider a one-dimensional array Z, build a two-dimensional array whose first row is (Z[0],Z[1],Z[2]) and each subsequent row is shifted by 1 (last row should be (Z[-3],Z[-2],Z[-1]) (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 150, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[0 1 2]\n", + " [1 2 3]\n", + " [2 3 4]\n", + " [3 4 5]\n", + " [4 5 6]\n", + " [5 6 7]\n", + " [6 7 8]\n", + " [7 8 9]]\n" + ] + } + ], + "source": [ + "from numpy.lib import stride_tricks\n", + "\n", + "def rolling(a, window):\n", + " shape = (a.size - window + 1, window)\n", + " strides = (a.itemsize, a.itemsize)\n", + " return stride_tricks.as_strided(a, shape=shape, strides=strides)\n", + "Z = rolling(np.arange(10), 3)\n", + "print(Z)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 77. How to negate a boolean, or to change the sign of a float inplace? (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 151, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "array([-0.60515123, 0.43549087, 0.52442456, 0.0356695 , -0.23883629,\n", + " -0.84143239, 0.19764735, -0.18077792, 0.13691257, 0.68599021,\n", + " -0.38823498, 0.38583286, 0.26095065, 0.73373092, 0.01910138,\n", + " 0.13498975, -0.52380018, 0.18579632, -0.59756718, 0.67430642,\n", + " -0.36618711, -0.17388824, 0.47300426, -0.13042448, -0.69316436,\n", + " -0.1209151 , 0.96355909, 0.92080749, -0.68705478, -0.81773626,\n", + " -0.81637611, -0.95952536, 0.94555061, 0.10849992, 0.37233389,\n", + " 0.91068372, 0.65122164, -0.1956454 , -0.80617708, 0.91380286,\n", + " -0.6473517 , 0.4823098 , 0.86612919, 0.27201003, -0.64399615,\n", + " -0.26976413, 0.63029974, 0.60577697, -0.08888142, 0.3809405 ,\n", + " -0.99837241, 0.9020259 , 0.6519518 , -0.49950213, -0.75413816,\n", + " -0.93755663, -0.97512816, 0.91808147, 0.15909129, -0.26003462,\n", + " 0.71510419, 0.98702818, 0.43206768, -0.57933859, 0.97025575,\n", + " -0.09054095, -0.53450864, 0.03220686, 0.7651035 , -0.20554131,\n", + " -0.42763552, 0.92331803, 0.22105698, -0.68239629, 0.61802196,\n", + " -0.9016358 , 0.84247899, -0.0685761 , 0.37265138, 0.1892566 ,\n", + " -0.11414986, -0.16512463, -0.59046412, -0.86893301, 0.8311934 ,\n", + " -0.25590966, -0.70750511, 0.4214799 , -0.68910026, -0.24770641,\n", + " 0.70216394, -0.88241126, -0.90412627, -0.26920122, -0.44894373,\n", + " 0.18573238, 0.41156297, -0.56693814, 0.1930838 , -0.27236135])" + ] + }, + "execution_count": 151, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "Z = np.random.randint(0,2,100)\n", + "np.logical_not(Z, out=Z)\n", + "\n", + "Z = np.random.uniform(-1.0,1.0,100)\n", + "np.negative(Z, out=Z)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 78. Consider 2 sets of points P0,P1 describing lines (2d) and a point p, how to compute distance from p to each line i (P0[i],P1[i])? (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 152, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[ 6.87747012 4.43402821 6.03081773 0.68229152 3.83914465 11.32381182\n", + " 6.02971498 3.8806894 2.60546498 8.60913116]\n" + ] + } + ], + "source": [ + "def distance(P0, P1, p):\n", + " T = P1 - P0\n", + " L = (T**2).sum(axis=1)\n", + " U = -((P0[:,0]-p[...,0])*T[:,0] + (P0[:,1]-p[...,1])*T[:,1]) / L\n", + " U = U.reshape(len(U),1)\n", + " D = P0 + U*T - p\n", + " return np.sqrt((D**2).sum(axis=1))\n", + "\n", + "P0 = np.random.uniform(-10,10,(10,2))\n", + "P1 = np.random.uniform(-10,10,(10,2))\n", + "p = np.random.uniform(-10,10,( 1,2))\n", + "print(distance(P0, P1, p))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 79. Consider 2 sets of points P0,P1 describing lines (2d) and a set of points P, how to compute distance from each point j (P[j]) to each line i (P0[i],P1[i])? (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 153, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[ 0.34715515 0.457134 3.4800939 12.12478968 8.20114654 5.00513812\n", + " 6.17297549 0.24367633 2.02273733 0.86902738]\n", + " [ 8.18808109 11.62821581 16.09927037 0.36086368 16.21096296 13.10996272\n", + " 18.51066545 5.20847391 6.90630671 0.54245396]\n", + " [ 3.95038303 2.62288699 4.90164439 11.66489844 4.31862226 1.1713101\n", + " 8.80271778 6.4339815 3.1167776 5.39329033]\n", + " [ 0.40540562 5.61926124 0.54415218 15.38593657 9.28879852 6.03357322\n", + " 1.29474364 5.62564882 4.79605062 5.96468922]\n", + " [ 8.36893468 0.22517888 1.55171643 15.42581351 0.06425435 3.21886961\n", + " 6.11226158 7.77164473 7.09647028 7.89696605]\n", + " [ 3.42311662 10.92927884 11.91687465 5.59853441 4.35042708 1.2910363\n", + " 16.80708538 14.39684831 5.65892813 11.81718496]\n", + " [ 3.52771882 2.13120704 6.81842428 8.48646892 12.01499082 8.83065809\n", + " 8.99763958 0.43754811 5.33005798 2.65755809]\n", + " [ 9.09317963 3.16689605 9.40107244 5.13925125 17.65705088 14.46037892\n", + " 10.48543485 4.13209943 11.08922781 7.47443214]\n", + " [ 4.577419 1.96264667 0.92456213 15.17209236 3.95665233 0.7622267\n", + " 4.3539982 2.3244283 2.08455727 2.19016199]\n", + " [ 1.64347194 6.24781345 0.67812639 15.24295517 10.59651124 7.32921824\n", + " 0.80285203 7.31741529 6.40032514 7.75620464]]\n" + ] + } + ], + "source": [ + "P0 = np.random.uniform(-10, 10, (10,2))\n", + "P1 = np.random.uniform(-10,10,(10,2))\n", + "p = np.random.uniform(-10, 10, (10,2))\n", + "print(np.array([distance(P0,P1,p_i) for p_i in p]))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 80. Consider an arbitrary array, write a function that extract a subpart with a fixed shape and centered on a given element (pad with a `fill` value when necessary) (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 154, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[0 4 8 6 0 8 6 9 7 0]\n", + " [1 2 6 5 3 8 9 1 0 5]\n", + " [8 2 8 4 9 8 4 8 0 6]\n", + " [1 1 3 8 5 9 8 2 9 9]\n", + " [5 8 4 5 9 1 9 1 9 1]\n", + " [2 2 8 0 5 3 7 5 6 4]\n", + " [5 6 5 3 2 4 7 3 8 8]\n", + " [1 2 3 2 9 5 8 3 7 0]\n", + " [3 7 4 2 3 7 4 6 7 3]\n", + " [7 5 8 3 9 0 2 9 1 8]]\n", + "[[0 0 0 0 0]\n", + " [0 0 4 8 6]\n", + " [0 1 2 6 5]\n", + " [0 8 2 8 4]\n", + " [0 1 1 3 8]]\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + ":23: FutureWarning: Using a non-tuple sequence for multidimensional indexing is deprecated; use `arr[tuple(seq)]` instead of `arr[seq]`. In the future this will be interpreted as an array index, `arr[np.array(seq)]`, which will result either in an error or a different result.\n", + " R[r] = Z[z]\n" + ] + } + ], + "source": [ + "Z = np.random.randint(0,10,(10,10))\n", + "shape = (5,5)\n", + "fill = 0\n", + "position = (1,1)\n", + "\n", + "R = np.ones(shape, dtype=Z.dtype)*fill\n", + "P = np.array(list(position)).astype(int)\n", + "Rs = np.array(list(R.shape)).astype(int)\n", + "Zs = np.array(list(Z.shape)).astype(int)\n", + "\n", + "R_start = np.zeros((len(shape),)).astype(int)\n", + "R_stop = np.array(list(shape)).astype(int)\n", + "Z_start = (P-Rs//2)\n", + "Z_stop = (P+Rs//2)+Rs%2\n", + "\n", + "R_start = (R_start - np.minimum(Z_start,0)).tolist()\n", + "Z_start = (np.maximum(Z_start,0)).tolist()\n", + "R_stop = np.maximum(R_start, (R_stop - np.maximum(Z_stop-Zs,0))).tolist()\n", + "Z_stop = (np.minimum(Z_stop,Zs)).tolist()\n", + "\n", + "r = [slice(start,stop) for start,stop in zip(R_start,R_stop)]\n", + "z = [slice(start,stop) for start,stop in zip(Z_start,Z_stop)]\n", + "R[r] = Z[z]\n", + "print(Z)\n", + "print(R)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 81. Consider an array Z = [1,2,3,4,5,6,7,8,9,10,11,12,13,14], how to generate an array R = [[1,2,3,4], [2,3,4,5], [3,4,5,6], ..., [11,12,13,14]]? (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 155, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[ 1 2 3 4]\n", + " [ 2 3 4 5]\n", + " [ 3 4 5 6]\n", + " [ 4 5 6 7]\n", + " [ 5 6 7 8]\n", + " [ 6 7 8 9]\n", + " [ 7 8 9 10]\n", + " [ 8 9 10 11]\n", + " [ 9 10 11 12]\n", + " [10 11 12 13]\n", + " [11 12 13 14]]\n" + ] + } + ], + "source": [ + "Z = np.arange(1,15,dtype=np.uint32)\n", + "R = stride_tricks.as_strided(Z,(11,4),(4,4))\n", + "print(R)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 82. Compute a matrix rank (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 156, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "10\n" + ] + } + ], + "source": [ + "Z = np.random.uniform(0,1,(10,10))\n", + "U, S, V = np.linalg.svd(Z) # Singular Value Decomposition\n", + "rank = np.sum(S > 1e-10)\n", + "print(rank)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 83. How to find the most frequent value in an array?" + ] + }, + { + "cell_type": "code", + "execution_count": 157, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1\n" + ] + } + ], + "source": [ + "Z = np.random.randint(0,10,50)\n", + "print(np.bincount(Z).argmax())\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 84. Extract all the contiguous 3x3 blocks from a random 10x10 matrix (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 158, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[[[0 0 2]\n", + " [0 1 4]\n", + " [1 1 0]]\n", + "\n", + " [[0 2 0]\n", + " [1 4 0]\n", + " [1 0 3]]\n", + "\n", + " [[2 0 1]\n", + " [4 0 3]\n", + " [0 3 1]]\n", + "\n", + " [[0 1 4]\n", + " [0 3 1]\n", + " [3 1 0]]\n", + "\n", + " [[1 4 0]\n", + " [3 1 3]\n", + " [1 0 1]]\n", + "\n", + " [[4 0 3]\n", + " [1 3 4]\n", + " [0 1 2]]\n", + "\n", + " [[0 3 1]\n", + " [3 4 1]\n", + " [1 2 0]]\n", + "\n", + " [[3 1 3]\n", + " [4 1 2]\n", + " [2 0 0]]]\n", + "\n", + "\n", + " [[[0 1 4]\n", + " [1 1 0]\n", + " [4 1 1]]\n", + "\n", + " [[1 4 0]\n", + " [1 0 3]\n", + " [1 1 1]]\n", + "\n", + " [[4 0 3]\n", + " [0 3 1]\n", + " [1 1 3]]\n", + "\n", + " [[0 3 1]\n", + " [3 1 0]\n", + " [1 3 4]]\n", + "\n", + " [[3 1 3]\n", + " [1 0 1]\n", + " [3 4 1]]\n", + "\n", + " [[1 3 4]\n", + " [0 1 2]\n", + " [4 1 2]]\n", + "\n", + " [[3 4 1]\n", + " [1 2 0]\n", + " [1 2 0]]\n", + "\n", + " [[4 1 2]\n", + " [2 0 0]\n", + " [2 0 1]]]\n", + "\n", + "\n", + " [[[1 1 0]\n", + " [4 1 1]\n", + " [2 4 0]]\n", + "\n", + " [[1 0 3]\n", + " [1 1 1]\n", + " [4 0 1]]\n", + "\n", + " [[0 3 1]\n", + " [1 1 3]\n", + " [0 1 0]]\n", + "\n", + " [[3 1 0]\n", + " [1 3 4]\n", + " [1 0 4]]\n", + "\n", + " [[1 0 1]\n", + " [3 4 1]\n", + " [0 4 4]]\n", + "\n", + " [[0 1 2]\n", + " [4 1 2]\n", + " [4 4 3]]\n", + "\n", + " [[1 2 0]\n", + " [1 2 0]\n", + " [4 3 3]]\n", + "\n", + " [[2 0 0]\n", + " [2 0 1]\n", + " [3 3 4]]]\n", + "\n", + "\n", + " [[[4 1 1]\n", + " [2 4 0]\n", + " [2 1 0]]\n", + "\n", + " [[1 1 1]\n", + " [4 0 1]\n", + " [1 0 0]]\n", + "\n", + " [[1 1 3]\n", + " [0 1 0]\n", + " [0 0 2]]\n", + "\n", + " [[1 3 4]\n", + " [1 0 4]\n", + " [0 2 4]]\n", + "\n", + " [[3 4 1]\n", + " [0 4 4]\n", + " [2 4 2]]\n", + "\n", + " [[4 1 2]\n", + " [4 4 3]\n", + " [4 2 2]]\n", + "\n", + " [[1 2 0]\n", + " [4 3 3]\n", + " [2 2 0]]\n", + "\n", + " [[2 0 1]\n", + " [3 3 4]\n", + " [2 0 4]]]\n", + "\n", + "\n", + " [[[2 4 0]\n", + " [2 1 0]\n", + " [4 2 1]]\n", + "\n", + " [[4 0 1]\n", + " [1 0 0]\n", + " [2 1 1]]\n", + "\n", + " [[0 1 0]\n", + " [0 0 2]\n", + " [1 1 2]]\n", + "\n", + " [[1 0 4]\n", + " [0 2 4]\n", + " [1 2 2]]\n", + "\n", + " [[0 4 4]\n", + " [2 4 2]\n", + " [2 2 2]]\n", + "\n", + " [[4 4 3]\n", + " [4 2 2]\n", + " [2 2 4]]\n", + "\n", + " [[4 3 3]\n", + " [2 2 0]\n", + " [2 4 3]]\n", + "\n", + " [[3 3 4]\n", + " [2 0 4]\n", + " [4 3 1]]]\n", + "\n", + "\n", + " [[[2 1 0]\n", + " [4 2 1]\n", + " [2 4 1]]\n", + "\n", + " [[1 0 0]\n", + " [2 1 1]\n", + " [4 1 0]]\n", + "\n", + " [[0 0 2]\n", + " [1 1 2]\n", + " [1 0 3]]\n", + "\n", + " [[0 2 4]\n", + " [1 2 2]\n", + " [0 3 2]]\n", + "\n", + " [[2 4 2]\n", + " [2 2 2]\n", + " [3 2 0]]\n", + "\n", + " [[4 2 2]\n", + " [2 2 4]\n", + " [2 0 0]]\n", + "\n", + " [[2 2 0]\n", + " [2 4 3]\n", + " [0 0 1]]\n", + "\n", + " [[2 0 4]\n", + " [4 3 1]\n", + " [0 1 3]]]\n", + "\n", + "\n", + " [[[4 2 1]\n", + " [2 4 1]\n", + " [4 1 4]]\n", + "\n", + " [[2 1 1]\n", + " [4 1 0]\n", + " [1 4 1]]\n", + "\n", + " [[1 1 2]\n", + " [1 0 3]\n", + " [4 1 2]]\n", + "\n", + " [[1 2 2]\n", + " [0 3 2]\n", + " [1 2 2]]\n", + "\n", + " [[2 2 2]\n", + " [3 2 0]\n", + " [2 2 1]]\n", + "\n", + " [[2 2 4]\n", + " [2 0 0]\n", + " [2 1 1]]\n", + "\n", + " [[2 4 3]\n", + " [0 0 1]\n", + " [1 1 2]]\n", + "\n", + " [[4 3 1]\n", + " [0 1 3]\n", + " [1 2 3]]]\n", + "\n", + "\n", + " [[[2 4 1]\n", + " [4 1 4]\n", + " [3 4 1]]\n", + "\n", + " [[4 1 0]\n", + " [1 4 1]\n", + " [4 1 3]]\n", + "\n", + " [[1 0 3]\n", + " [4 1 2]\n", + " [1 3 4]]\n", + "\n", + " [[0 3 2]\n", + " [1 2 2]\n", + " [3 4 0]]\n", + "\n", + " [[3 2 0]\n", + " [2 2 1]\n", + " [4 0 1]]\n", + "\n", + " [[2 0 0]\n", + " [2 1 1]\n", + " [0 1 3]]\n", + "\n", + " [[0 0 1]\n", + " [1 1 2]\n", + " [1 3 2]]\n", + "\n", + " [[0 1 3]\n", + " [1 2 3]\n", + " [3 2 4]]]]\n" + ] + } + ], + "source": [ + "Z = np.random.randint(0,5,(10,10))\n", + "n = 3\n", + "i = 1 + (Z.shape[0]-3)\n", + "j = 1 + (Z.shape[1]-3)\n", + "C = stride_tricks.as_strided(Z, shape=(i, j, n, n), strides=Z.strides + Z.strides)\n", + "print(C)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 85. Create a 2D array subclass such that Z[i,j] == Z[j,i] (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 159, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[ 8 13 15 5 11]\n", + " [13 5 15 5 14]\n", + " [15 15 1 42 3]\n", + " [ 5 5 42 9 11]\n", + " [11 14 3 11 5]]\n" + ] + } + ], + "source": [ + "class Symetric(np.ndarray):\n", + " def __setitem__(self, index, value):\n", + " i,j = index\n", + " super(Symetric, self).__setitem__((i,j), value)\n", + " super(Symetric, self).__setitem__((j,i), value)\n", + "\n", + "def symetric(Z):\n", + " return np.asarray(Z + Z.T - np.diag(Z.diagonal())).view(Symetric)\n", + "\n", + "S = symetric(np.random.randint(0,10,(5,5)))\n", + "S[2,3] = 42\n", + "print(S)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 86. Consider a set of p matrices wich shape (n,n) and a set of p vectors with shape (n,1). How to compute the sum of of the p matrix products at once? (result has shape (n,1)) (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 160, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[200.]\n", + " [200.]\n", + " [200.]\n", + " [200.]\n", + " [200.]\n", + " [200.]\n", + " [200.]\n", + " [200.]\n", + " [200.]\n", + " [200.]\n", + " [200.]\n", + " [200.]\n", + " [200.]\n", + " [200.]\n", + " [200.]\n", + " [200.]\n", + " [200.]\n", + " [200.]\n", + " [200.]\n", + " [200.]]\n" + ] + } + ], + "source": [ + "p, n = 10, 20\n", + "M = np.ones((p,n,n))\n", + "V = np.ones((p,n,1))\n", + "S = np.tensordot(M, V, axes=[[0, 2], [0, 1]])\n", + "print(S)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 87. Consider a 16x16 array, how to get the block-sum (block size is 4x4)? (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 161, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[16. 16. 16. 16.]\n", + " [16. 16. 16. 16.]\n", + " [16. 16. 16. 16.]\n", + " [16. 16. 16. 16.]]\n" + ] + } + ], + "source": [ + "Z = np.ones((16,16))\n", + "k = 4\n", + "S = np.add.reduceat(np.add.reduceat(Z, np.arange(0, Z.shape[0], k), axis=0),\n", + " np.arange(0, Z.shape[1], k), axis=1)\n", + "print(S)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 88. How to implement the Game of Life using numpy arrays? (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 162, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n", + " 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n", + " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n", + " 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n", + " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n", + " 0 0 0 1 0 0 0 0 0 0 0 0 0 0]\n", + " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n", + " 0 0 0 1 0 0 0 0 0 0 0 0 0 0]\n", + " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n", + " 0 0 0 1 0 0 0 0 0 0 0 0 0 0]\n", + " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n", + " 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n", + " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n", + " 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n", + " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n", + " 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n", + " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n", + " 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n", + " [0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0\n", + " 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n", + " [0 0 0 0 0 0 0 0 0 0 0 1 1 0 1 1 1 0 1 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 0 0\n", + " 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n", + " [0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0\n", + " 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n", + " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0\n", + " 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n", + " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0\n", + " 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n", + " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 1 0 0 0 0 0\n", + " 0 0 0 0 0 0 0 0 0 0 1 0 0 0]\n", + " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0\n", + " 0 0 0 0 0 0 0 0 1 1 0 1 0 0]\n", + " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n", + " 0 0 0 0 0 0 0 0 1 0 0 1 0 0]\n", + " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 1 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0\n", + " 0 0 0 0 0 0 0 0 1 0 0 0 0 0]\n", + " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 1 0 0\n", + " 0 0 0 0 0 0 0 0 0 0 0 1 0 0]\n", + " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 1 0 0 0 0 0 0 1 0 0 0 0 1 1 0 0 0\n", + " 0 0 0 0 0 0 0 0 0 1 1 0 1 0]\n", + " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 1 1 0 0 1 1 1 0 0 0\n", + " 0 0 0 0 0 0 0 0 1 0 0 1 1 0]\n", + " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 1 0 0 0 0 0 0 0 1 1 0 0 0 0 0 1 0 0\n", + " 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n", + " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 1 1 0 0 0 1 0 0 1 1 0 0 1 0 0\n", + " 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n", + " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 1 1 1 0 0 0 1 0 1 1 0 1 1 0 0\n", + " 0 0 0 0 0 0 0 0 0 1 0 1 0 0]\n", + " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 1 1 0 0 0 1 0 1 0 1 0 1 0 0 0 0\n", + " 0 0 0 0 0 0 0 0 0 1 1 1 0 0]\n", + " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 1 1 0 0 0 0 0\n", + " 0 0 0 0 0 0 0 0 0 0 1 0 0 0]\n", + " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 1 0 0 0 1 1 1 0 0 0 0 0 0\n", + " 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n", + " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0\n", + " 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n", + " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0\n", + " 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n", + " [0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 1 0 0 0 0\n", + " 0 1 0 0 0 0 0 0 0 0 0 0 0 0]\n", + " [0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 1 1 0 0 0 1 0 1 0 0 0\n", + " 1 0 1 0 0 0 0 0 1 1 1 0 0 0]\n", + " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 1 0 0 0 0 1 0 0 0 0 1 0 1 0 0 1\n", + " 0 0 1 0 0 0 0 0 0 0 0 0 0 0]\n", + " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0\n", + " 1 1 0 0 0 0 0 0 0 0 0 0 0 0]\n", + " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n", + " 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n", + " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0\n", + " 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n", + " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 1 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0\n", + " 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n", + " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 1 0 1 0 0 0 0 0 1 1 0 0 0 0 0 0\n", + " 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n", + " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0\n", + " 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n", + " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n", + " 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n", + " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n", + " 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n", + " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n", + " 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n", + " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n", + " 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n", + " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n", + " 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n", + " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n", + " 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n", + " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n", + " 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n", + " [0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n", + " 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n", + " [0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n", + " 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n", + " [0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n", + " 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n", + " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n", + " 0 0 0 0 0 0 0 0 0 0 0 0 0 0]\n", + " [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n", + " 0 0 0 0 0 0 0 0 0 0 0 0 0 0]]\n" + ] + } + ], + "source": [ + "def iterate(Z):\n", + " # Count neighbours\n", + " N = (Z[0:-2,0:-2] + Z[0:-2,1:-1] + Z[0:-2,2:] +\n", + " Z[1:-1,0:-2] + Z[1:-1,2:] +\n", + " Z[2: ,0:-2] + Z[2: ,1:-1] + Z[2: ,2:])\n", + "\n", + " # Apply rules\n", + " birth = (N==3) & (Z[1:-1,1:-1]==0)\n", + " survive = ((N==2) | (N==3)) & (Z[1:-1,1:-1]==1)\n", + " Z[...] = 0\n", + " Z[1:-1,1:-1][birth | survive] = 1\n", + " return Z\n", + "\n", + "Z = np.random.randint(0,2,(50,50))\n", + "for i in range(100): Z = iterate(Z)\n", + "print(Z)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 89. How to get the n largest values of an array (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 163, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[9995 9996 9997 9998 9999]\n", + "[9998 9999 9997 9996 9995]\n" + ] + } + ], + "source": [ + "Z = np.arange(10000)\n", + "np.random.shuffle(Z)\n", + "n = 5\n", + "\n", + "# Slow\n", + "print (Z[np.argsort(Z)[-n:]])\n", + "\n", + "# Fast\n", + "print (Z[np.argpartition(-Z,n)[:n]])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 90. Given an arbitrary number of vectors, build the cartesian product (every combinations of every item) (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 164, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[1 4 6]\n", + " [1 4 7]\n", + " [1 5 6]\n", + " [1 5 7]\n", + " [2 4 6]\n", + " [2 4 7]\n", + " [2 5 6]\n", + " [2 5 7]\n", + " [3 4 6]\n", + " [3 4 7]\n", + " [3 5 6]\n", + " [3 5 7]]\n" + ] + } + ], + "source": [ + "def cartesian(arrays):\n", + " arrays = [np.asarray(a) for a in arrays]\n", + " shape = (len(x) for x in arrays)\n", + "\n", + " ix = np.indices(shape, dtype=int)\n", + " ix = ix.reshape(len(arrays), -1).T\n", + "\n", + " for n, arr in enumerate(arrays):\n", + " ix[:, n] = arrays[n][ix[:, n]]\n", + "\n", + " return ix\n", + "\n", + "print (cartesian(([1, 2, 3], [4, 5], [6, 7])))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 91. How to create a record array from a regular array? (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 165, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[(b'Hello', 2.5, 3) (b'World', 3.6, 2)]\n" + ] + } + ], + "source": [ + "Z = np.array([(\"Hello\", 2.5, 3),\n", + " (\"World\", 3.6, 2)])\n", + "R = np.core.records.fromarrays(Z.T,\n", + " names='col1, col2, col3',\n", + " formats = 'S8, f8, i8')\n", + "print(R)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 92. Consider a large vector Z, compute Z to the power of 3 using 3 different methods (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 170, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1.95 s ± 63.9 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n", + "582 ms ± 38.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n", + "325 ms ± 11.6 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n" + ] + } + ], + "source": [ + "x = np.random.rand(int(5e7))\n", + "%timeit np.power(x,3)\n", + "%timeit x*x*x\n", + "%timeit np.einsum('i,i,i->i',x,x,x)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 93. Consider two arrays A and B of shape (8,3) and (2,2). How to find rows of A that contain elements of each row of B regardless of the order of the elements in B? (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 169, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[3 6 7]\n" + ] + } + ], + "source": [ + "A = np.random.randint(0,5,(8,3))\n", + "B = np.random.randint(0,5,(2,2))\n", + "\n", + "C = (A[..., np.newaxis, np.newaxis] == B)\n", + "rows = np.where(C.any((3,1)).all(1))[0]\n", + "print(rows)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 94. Considering a 10x3 matrix, extract rows with unequal values (e.g. [2,2,3]) (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 172, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[0 1 2]\n", + " [0 1 3]\n", + " [3 0 0]\n", + " [2 2 1]\n", + " [3 0 3]\n", + " [4 2 0]\n", + " [0 1 2]\n", + " [0 3 2]\n", + " [4 3 2]\n", + " [0 4 0]]\n", + "[[0 1 2]\n", + " [0 1 3]\n", + " [3 0 0]\n", + " [2 2 1]\n", + " [3 0 3]\n", + " [4 2 0]\n", + " [0 1 2]\n", + " [0 3 2]\n", + " [4 3 2]\n", + " [0 4 0]]\n", + "[[0 1 2]\n", + " [0 1 3]\n", + " [3 0 0]\n", + " [2 2 1]\n", + " [3 0 3]\n", + " [4 2 0]\n", + " [0 1 2]\n", + " [0 3 2]\n", + " [4 3 2]\n", + " [0 4 0]]\n" + ] + } + ], + "source": [ + "Z = np.random.randint(0,5,(10,3))\n", + "print(Z)\n", + "# solution for arrays of all dtypes (including string arrays and record arrays)\n", + "E = np.all(Z[:,1:] == Z[:,:-1], axis=1)\n", + "U = Z[~E]\n", + "print(U)\n", + "# soluiton for numerical arrays only, will work for any number of columns in Z\n", + "U = Z[Z.max(axis=1) != Z.min(axis=1),:]\n", + "print(U)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 95. Convert a vector of ints into a matrix binary representation (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 173, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[0 0 0 0 0 0 0 0]\n", + " [0 0 0 0 0 0 0 1]\n", + " [0 0 0 0 0 0 1 0]\n", + " [0 0 0 0 0 0 1 1]\n", + " [0 0 0 0 1 1 1 1]\n", + " [0 0 0 1 0 0 0 0]\n", + " [0 0 1 0 0 0 0 0]\n", + " [0 1 0 0 0 0 0 0]\n", + " [1 0 0 0 0 0 0 0]]\n", + "[[0 0 0 0 0 0 0 0]\n", + " [0 0 0 0 0 0 0 1]\n", + " [0 0 0 0 0 0 1 0]\n", + " [0 0 0 0 0 0 1 1]\n", + " [0 0 0 0 1 1 1 1]\n", + " [0 0 0 1 0 0 0 0]\n", + " [0 0 1 0 0 0 0 0]\n", + " [0 1 0 0 0 0 0 0]\n", + " [1 0 0 0 0 0 0 0]]\n" + ] + } + ], + "source": [ + "I = np.array([0, 1, 2, 3, 15, 16, 32, 64, 128])\n", + "B = ((I.reshape(-1,1) & (2**np.arange(8))) != 0).astype(int)\n", + "print(B[:,::-1])\n", + "\n", + "# Author: Daniel T. McDonald\n", + "\n", + "I = np.array([0, 1, 2, 3, 15, 16, 32, 64, 128], dtype=np.uint8)\n", + "print(np.unpackbits(I[:, np.newaxis], axis=1))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 96. Given a two dimensional array, how to extract unique rows? (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 174, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[0 0 1]\n", + " [0 1 0]\n", + " [1 1 0]\n", + " [1 1 1]]\n", + "[[0 0 1]\n", + " [0 1 0]\n", + " [1 1 0]\n", + " [1 1 1]]\n" + ] + } + ], + "source": [ + "Z = np.random.randint(0,2,(6,3))\n", + "T = np.ascontiguousarray(Z).view(np.dtype((np.void, Z.dtype.itemsize * Z.shape[1])))\n", + "_, idx = np.unique(T, return_index=True)\n", + "uZ = Z[idx]\n", + "print(uZ)\n", + "\n", + "# Author: Andreas Kouzelis\n", + "# NumPy >= 1.13\n", + "uZ = np.unique(Z, axis=0)\n", + "print(uZ)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 97. Considering 2 vectors A & B, write the einsum equivalent of inner, outer, sum, and mul function (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 175, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "array([[0.12640427, 0.07248879, 0.23831993, 0.37415378, 0.5571371 ,\n", + " 0.34444972, 0.19960691, 0.04497255, 0.29909482, 0.07049955],\n", + " [0.07935799, 0.04550926, 0.14961988, 0.23489786, 0.34977681,\n", + " 0.21624933, 0.12531542, 0.02823426, 0.18777502, 0.04426039],\n", + " [0.04712269, 0.02702335, 0.08884412, 0.13948209, 0.20769708,\n", + " 0.12840861, 0.07441216, 0.01676547, 0.1115006 , 0.02628177],\n", + " [0.13905427, 0.07974316, 0.26216998, 0.4115975 , 0.61289301,\n", + " 0.37892078, 0.21958272, 0.04947321, 0.32902696, 0.07755484],\n", + " [0.19964571, 0.11449041, 0.37640779, 0.59094679, 0.87995471,\n", + " 0.54403154, 0.31526359, 0.07103065, 0.472397 , 0.11134855],\n", + " [0.20567997, 0.11795086, 0.38778466, 0.60880806, 0.90655121,\n", + " 0.56047481, 0.32479238, 0.07317754, 0.48667513, 0.11471404],\n", + " [0.03219392, 0.01846218, 0.06069774, 0.09529328, 0.14189733,\n", + " 0.08772795, 0.05083791, 0.01145407, 0.0761765 , 0.01795554],\n", + " [0.08865162, 0.05083886, 0.16714188, 0.26240678, 0.39073922,\n", + " 0.24157432, 0.13999112, 0.03154078, 0.20976538, 0.04944373],\n", + " [0.06440877, 0.03693636, 0.12143494, 0.19064851, 0.28388691,\n", + " 0.17551293, 0.10170888, 0.02291558, 0.15240253, 0.03592275],\n", + " [0.09789941, 0.05614217, 0.18457747, 0.28978003, 0.43149961,\n", + " 0.2667744 , 0.15459445, 0.03483099, 0.23164729, 0.05460151]])" + ] + }, + "execution_count": 175, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "A = np.random.uniform(0,1,10)\n", + "B = np.random.uniform(0,1,10)\n", + "\n", + "np.einsum('i->', A) \n", + "np.einsum('i,i->i', A, B) \n", + "np.einsum('i,i', A, B) \n", + "np.einsum('i,j->ij', A, B)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 98. Considering a path described by two vectors (X,Y), how to sample it using equidistant samples (???)?" + ] + }, + { + "cell_type": "code", + "execution_count": 176, + "metadata": {}, + "outputs": [], + "source": [ + "phi = np.arange(0, 10*np.pi, 0.1)\n", + "a = 1\n", + "x = a*phi*np.cos(phi)\n", + "y = a*phi*np.sin(phi)\n", + "\n", + "dr = (np.diff(x)**2 + np.diff(y)**2)**.5 # segment lengths\n", + "r = np.zeros_like(x)\n", + "r[1:] = np.cumsum(dr) # integrate path\n", + "r_int = np.linspace(0, r.max(), 200) # regular spaced path\n", + "x_int = np.interp(r_int, r, x) # integrate path\n", + "y_int = np.interp(r_int, r, y)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 99. Given an integer n and a 2D array X, select from X the rows which can be interpreted as draws from a multinomial distribution with n degrees, i.e., the rows which only contain integers and which sum to n. (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 177, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[2. 0. 1. 1.]]\n" + ] + } + ], + "source": [ + "X = np.asarray([[1.0, 0.0, 3.0, 8.0],\n", + " [2.0, 0.0, 1.0, 1.0],\n", + " [1.5, 2.5, 1.0, 0.0]])\n", + "n = 4\n", + "M = np.logical_and.reduce(np.mod(X, 1) == 0, axis=-1)\n", + "M &= (X.sum(axis=-1) == n)\n", + "print(X[M])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 100. Compute bootstrapped 95% confidence intervals for the mean of a 1D array X (i.e., resample the elements of an array with replacement N times, compute the mean of each sample, and then compute percentiles over the means). (???)" + ] + }, + { + "cell_type": "code", + "execution_count": 178, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[-0.08212 0.3042375]\n" + ] + } + ], + "source": [ + "X = np.random.randn(100) # random 1D array\n", + "N = 1000 # number of bootstrap samples\n", + "idx = np.random.randint(0, X.size, (N, X.size))\n", + "means = X[idx].mean(axis=1)\n", + "confint = np.percentile(means, [2.5, 97.5])\n", + "print(confint)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.8.3" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/Week1/work.py b/Week1/work.py index 9c53179..e3b7a91 100644 --- a/Week1/work.py +++ b/Week1/work.py @@ -12,7 +12,7 @@ def demo(x): ''' ## Code Here - return None + return x*x def is_palindrome(string): ''' @@ -25,7 +25,14 @@ def is_palindrome(string): ''' ## Code Here - return None + reversed_string = string[::-1] + + if reversed_string == string: + return bool(1) + else: + return bool(0) + + def sqrt_of_numbers(num): ''' @@ -37,7 +44,7 @@ def sqrt_of_numbers(num): ''' ## Code Here - return None + return np.sqrt(abs(num)) def Maximum(arr): ''' @@ -50,7 +57,9 @@ def Maximum(arr): ''' ## Code Here - return None + x1 = np.sort(arr)[-1] + x2 = np.sort(arr)[-2] + return x1,x2 def even_sort(arr): ''' @@ -67,7 +76,24 @@ def even_sort(arr): ''' ## Code Here - return None + even = [] + odd = [] + + for i in arr: + if i %2 == 0: + even.append(i) + else: + odd.append(i) + + even = np.sort(even) + odd = np.sort(odd) + + arr =[] + for i in even: + arr.append(i) + for i in odd: + arr.append(i) + return arr def eqn_solver(A, B, C): @@ -88,4 +114,18 @@ def eqn_solver(A, B, C): ''' ## Code Here - return None + x1, x2 = A + y1, y2 = B + c1, c2 = C + + coeff_matrix = np.array([[x1, y1], [x2, y2]]) + const_matrix = np.array([[c1], [c2]]) + inverse = np.linalg.inv(coeff_matrix) + actual = np.dot(inverse,const_matrix) + d = actual.reshape(1,-1) + x = d[0][0] + y = d[0][1] + + return x,y + +