[
  {
    "path": ".gitattributes",
    "content": "*.md linguist-language=Python\n*.ipynb linguist-language=Python\n"
  },
  {
    "path": ".github/FUNDING.yml",
    "content": "# These are supported funding model platforms\n\ngithub: rougier # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]\n"
  },
  {
    "path": ".github/workflows/generate_solutions_files.yml",
    "content": "name: Generate Solutions Files\n\non:\n  push:\n    branches:\n      - master\n    paths:\n      - source/exercises100.ktx\n\njobs:\n  generate_files:\n    runs-on: ubuntu-22.04 # Python 3.7 is not supported on latest Ubuntu\n\n    permissions:\n      contents: write\n\n    steps:\n      - name: Checkout repository\n        uses: actions/checkout@v4\n\n      - name: Setup Python\n        uses: actions/setup-python@v5\n        with:\n          python-version: '3.7'\n          cache: 'pip'\n\n      - name: Install dependencies\n        run: pip3 install -r requirements.txt\n\n      - name: Generate solutions files\n        run: python3 generators.py\n\n      - name: Set environment variables\n        run: echo \"SHA_SHORT=$(git rev-parse --short $GITHUB_SHA)\" >> $GITHUB_ENV\n\n      - name: Commit changes\n        uses: stefanzweifel/git-auto-commit-action@v5\n        with:\n          commit_message: \"solutions update from ${{ env.SHA_SHORT }}\"\n          file_pattern: >\n            100_Numpy_exercises.ipynb\n            100_Numpy_random.ipynb\n            100_Numpy_exercises.md\n            100_Numpy_exercises_with_hints.md\n            100_Numpy_exercises_with_hints_with_solutions.md\n            100_Numpy_exercises_with_solutions.md\n"
  },
  {
    "path": ".gitignore",
    "content": ".ipynb_checkpoints/\n__pycache__\nvenv\n.idea\n.vscode\nUntitled.ipynb\n"
  },
  {
    "path": "100_Numpy_exercises.ipynb",
    "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"24963653\",\n   \"metadata\": {},\n   \"source\": [\n    \"# 100 numpy exercises\\n\",\n    \"\\n\",\n    \"This is a collection of exercises that have been collected in the numpy mailing list, on stack overflow\\n\",\n    \"and in the numpy documentation. The goal of this collection is to offer a quick reference for both old\\n\",\n    \"and new users but also to provide a set of exercises for those who teach.\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"If you find an error or think you've a better way to solve some of them, feel\\n\",\n    \"free to open an issue at <https://github.com/rougier/numpy-100>.\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"59ddae7e\",\n   \"metadata\": {},\n   \"source\": [\n    \"File automatically generated. See the documentation to update questions/answers/hints programmatically.\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"4a02b98c\",\n   \"metadata\": {},\n   \"source\": [\n    \"Run the `initialise.py` module, then for each question you can query the\\n\",\n    \"answer or an hint with `hint(n)` or `answer(n)` for `n` question number.\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"c2161124\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"%run initialise.py\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"96fe6659\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 1. Import the numpy package under the name `np` (★☆☆)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"9ffea9a1\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"126932fd\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 2. Print the numpy version and the configuration (★☆☆)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"fdd0d7a8\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"43c84f29\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 3. Create a null vector of size 10 (★☆☆)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"e007a9d1\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"22dc97de\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 4. How to find the memory size of any array (★☆☆)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"d27dba65\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"4e5bae8d\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 5. How to get the documentation of the numpy add function from the command line? (★☆☆)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"1dbbbed8\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"fcfdbff1\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 6. Create a null vector of size 10 but the fifth value which is 1 (★☆☆)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"0387a362\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"bdf2ba90\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 7. Create a vector with values ranging from 10 to 49 (★☆☆)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"81f0a925\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"5d0c6cfe\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 8. Reverse a vector (first element becomes last) (★☆☆)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"8e7754ae\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"3f5bef92\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 9. Create a 3x3 matrix with values ranging from 0 to 8 (★☆☆)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"e0e277fc\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"14b44c2e\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 10. Find indices of non-zero elements from [1,2,0,0,4,0] (★☆☆)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"1ad14e21\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"67c0f072\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 11. Create a 3x3 identity matrix (★☆☆)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"ca2bc573\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"097460e8\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 12. Create a 3x3x3 array with random values (★☆☆)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"4bd63c1f\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"f7a72443\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 13. Create a 10x10 array with random values and find the minimum and maximum values (★☆☆)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"86d85900\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"2100731f\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 14. Create a random vector of size 30 and find the mean value (★☆☆)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"63e2bbf2\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"dfb30185\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 15. Create a 2d array with 1 on the border and 0 inside (★☆☆)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"480afa6b\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"36e4de87\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 16. How to add a border (filled with 0's) around an existing array? (★☆☆)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"5ac52150\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"6f43f816\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 17. What is the result of the following expression? (★☆☆)\\n\",\n    \"```python\\n\",\n    \"0 * np.nan\\n\",\n    \"np.nan == np.nan\\n\",\n    \"np.inf > np.nan\\n\",\n    \"np.nan - np.nan\\n\",\n    \"np.nan in set([np.nan])\\n\",\n    \"0.3 == 3 * 0.1\\n\",\n    \"```\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"f2395fda\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"446f87e0\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 18. Create a 5x5 matrix with values 1,2,3,4 just below the diagonal (★☆☆)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"58d0e495\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"b6366cdb\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 19. Create a 8x8 matrix and fill it with a checkerboard pattern (★☆☆)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"54d459ce\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"35077361\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 20. Consider a (6,7,8) shape array, what is the index (x,y,z) of the 100th element? (★☆☆)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"d9cbcf85\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"ef02a06b\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 21. Create a checkerboard 8x8 matrix using the tile function (★☆☆)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"a29c4af1\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"4fc8f909\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 22. Normalize a 5x5 random matrix (★☆☆)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"ddb836b9\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"b2083fc7\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 23. Create a custom dtype that describes a color as four unsigned bytes (RGBA) (★☆☆)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"28bd9e0b\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"8bfb605c\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 24. Multiply a 5x3 matrix by a 3x2 matrix (real matrix product) (★☆☆)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"0e4525f6\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"d945b917\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 25. Given a 1D array, negate all elements which are between 3 and 8, in place. (★☆☆)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"13ea9d0c\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"80e3937d\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 26. What is the output of the following script? (★☆☆)\\n\",\n    \"```python\\n\",\n    \"# Author: Jake VanderPlas\\n\",\n    \"\\n\",\n    \"print(sum(range(5),-1))\\n\",\n    \"from numpy import *\\n\",\n    \"print(sum(range(5),-1))\\n\",\n    \"```\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"3268939a\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"4e586977\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 27. Consider an integer vector Z, which of these expressions are legal? (★☆☆)\\n\",\n    \"```python\\n\",\n    \"Z**Z\\n\",\n    \"2 << Z >> 2\\n\",\n    \"Z <- Z\\n\",\n    \"1j*Z\\n\",\n    \"Z/1/1\\n\",\n    \"Z<Z>Z\\n\",\n    \"```\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"1f36c9d4\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"4db5a6d5\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 28. What are the result of the following expressions? (★☆☆)\\n\",\n    \"```python\\n\",\n    \"np.array(0) / np.array(0)\\n\",\n    \"np.array(0) // np.array(0)\\n\",\n    \"np.array([np.nan]).astype(int).astype(float)\\n\",\n    \"```\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"a38701d1\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"b4d3080a\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 29. How to round away from zero a float array ? (★☆☆)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"84c7b39e\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"4f89952c\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 30. How to find common values between two arrays? (★☆☆)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"ec4561c9\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"26bf6974\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 31. How to ignore all numpy warnings (not recommended)? (★☆☆)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"950d597f\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"261fd76b\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 32. Is the following expressions true? (★☆☆)\\n\",\n    \"```python\\n\",\n    \"np.sqrt(-1) == np.emath.sqrt(-1)\\n\",\n    \"```\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"96eb8b24\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"4a82256f\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 33. How to get the dates of yesterday, today and tomorrow? (★☆☆)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"4cff80dd\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"d90599b6\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 34. How to get all the dates corresponding to the month of July 2016? (★★☆)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"16337844\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"aa35839c\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 35. How to compute ((A+B)*(-A/2)) in place (without copy)? (★★☆)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"54b8178b\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"13bc061a\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 36. Extract the integer part of a random array of positive numbers using 4 different methods (★★☆)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"c8fee789\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"f01b9650\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 37. Create a 5x5 matrix with row values ranging from 0 to 4 (★★☆)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"ab1101be\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"35976e4b\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 38. Consider a generator function that generates 10 integers and use it to build an array (★☆☆)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"7ca66207\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"edb9a160\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 39. Create a vector of size 10 with values ranging from 0 to 1, both excluded (★★☆)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"67aaf30a\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"69a3604b\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 40. Create a random vector of size 10 and sort it (★★☆)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"278e79e3\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"05ec5273\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 41. How to sum a small array faster than np.sum? (★★☆)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"94eea81d\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"d310ff7e\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 42. Consider two random arrays A and B, check if they are equal (★★☆)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"754e9de5\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"dab5009d\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 43. Make an array immutable (read-only) (★★☆)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"496ac553\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"71643a79\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 44. Consider a random 10x2 matrix representing cartesian coordinates, convert them to polar coordinates (★★☆)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"60d87877\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"8ed31762\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 45. Create random vector of size 10 and replace the maximum value by 0 (★★☆)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"6097ec5e\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"1a0d5a6b\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 46. Create a structured array with `x` and `y` coordinates covering the [0,1]x[0,1] area (★★☆)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"749e196f\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"ebc0da7d\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 47. Given two arrays, X and Y, construct the Cauchy matrix C (Cij =1/(xi - yj)) (★★☆)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"eb21da87\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"8f3327cb\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 48. Print the minimum and maximum representable values for each numpy scalar type (★★☆)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"3f197c5a\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"207e37c6\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 49. How to print all the values of an array? (★★☆)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"b9165f3d\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"1bda9a9a\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 50. How to find the closest value (to a given scalar) in a vector? (★★☆)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"86771556\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"0f057548\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 51. Create a structured array representing a position (x,y) and a color (r,g,b) (★★☆)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"b71873c2\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"47118bd1\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 52. Consider a random vector with shape (100,2) representing coordinates, find point by point distances (★★☆)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"567883c7\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"21d6ebad\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 53. How to convert a float (32 bits) array into an integer (32 bits) array in place?\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"c27bac6f\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"0c71ff26\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 54. How to read the following file? (★★☆)\\n\",\n    \"```\\n\",\n    \"1, 2, 3, 4, 5\\n\",\n    \"6,  ,  , 7, 8\\n\",\n    \" ,  , 9,10,11\\n\",\n    \"```\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"efdf3972\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"5953f719\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 55. What is the equivalent of enumerate for numpy arrays? (★★☆)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"d7e34455\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"87ded306\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 56. Generate a generic 2D Gaussian-like array (★★☆)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"171a6cbc\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"fcfd2f70\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 57. How to randomly place p elements in a 2D array? (★★☆)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"1804e4ab\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"f0b9b18b\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 58. Subtract the mean of each row of a matrix (★★☆)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"eac4c892\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"61e40ad7\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 59. How to sort an array by the nth column? (★★☆)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"c687d9f1\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"9a4f7fb1\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 60. How to tell if a given 2D array has null columns? (★★☆)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"021aa204\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"bff8d09f\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 61. Find the nearest value from a given value in an array (★★☆)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"a340d3dc\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"033f7e4e\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 62. Considering two arrays with shape (1,3) and (3,1), how to compute their sum using an iterator? (★★☆)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"f7bc41aa\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"8035a7b7\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 63. Create an array class that has a name attribute (★★☆)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"0f19321f\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"fa4dbf31\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 64. Consider a given vector, how to add 1 to each element indexed by a second vector (be careful with repeated indices)? (★★★)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"85893b93\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"d55ea9ef\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 65. How to accumulate elements of a vector (X) to an array (F) based on an index list (I)? (★★★)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"7241b03f\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"3d5ad91f\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 66. Considering a (w,h,3) image of (dtype=ubyte), compute the number of unique colors (★★☆)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"2f8d8c18\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"e4c0ca46\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 67. Considering a four dimensions array, how to get sum over the last two axis at once? (★★★)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"cb30cb50\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"68781ae8\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 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? (★★★)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"a1a09f76\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"42ec30c3\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 69. How to get the diagonal of a dot product? (★★★)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"77008bcb\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"72cd1881\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 70. Consider the vector [1, 2, 3, 4, 5], how to build a new vector with 3 consecutive zeros interleaved between each value? (★★★)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"d237d266\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"00e60dbf\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 71. Consider an array of dimension (5,5,3), how to multiply it by an array with dimensions (5,5)? (★★★)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"55f0e1d4\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"0ba31fcd\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 72. How to swap two rows of an array? (★★★)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"9fd8d80e\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"84f66062\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 73. Consider a set of 10 triplets describing 10 triangles (with shared vertices), find the set of unique line segments composing all the  triangles (★★★)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"3d92aac2\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"18c7d944\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 74. Given a sorted array C that corresponds to a bincount, how to produce an array A such that np.bincount(A) == C? (★★★)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"1f82e01e\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"de0fbc43\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 75. How to compute averages using a sliding window over an array? (★★★)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"7d6d173f\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"3caf673b\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 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]) (★★★)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"1b51c8bc\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"55ae7213\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 77. How to negate a boolean, or to change the sign of a float inplace? (★★★)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"f09474c7\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"453aed20\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 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])? (★★★)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"288111ad\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"a2242b1e\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 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])? (★★★)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"1238f08b\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"07c63697\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 80. Consider an arbitrary array, write a function that extracts a subpart with a fixed shape and centered on a given element (pad with a `fill` value when necessary) (★★★)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"01e418e9\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"8f46a3e6\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 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]]? (★★★)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"645a43d1\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"339d1830\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 82. Compute a matrix rank (★★★)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"55909d61\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"94599b6d\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 83. How to find the most frequent value in an array?\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"cb701ed6\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"3f2ff8f2\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 84. Extract all the contiguous 3x3 blocks from a random 10x10 matrix (★★★)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"93e6f167\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"f70e04be\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 85. Create a 2D array subclass such that Z[i,j] == Z[j,i] (★★★)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"795e513d\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"08da7b7a\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 86. Consider a set of p matrices with 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)) (★★★)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"9890ed56\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"7853fe1e\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 87. Consider a 16x16 array, how to get the block-sum (block size is 4x4)? (★★★)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"146e3ada\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"2421dc6d\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 88. How to implement the Game of Life using numpy arrays? (★★★)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"06ade5e0\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"57aee892\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 89. How to get the n largest values of an array (★★★)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"29d72cd2\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"0e2da2b5\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 90. Given an arbitrary number of vectors, build the cartesian product (every combination of every item) (★★★)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"54874b32\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"2ed5c735\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 91. How to create a record array from a regular array? (★★★)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"4e826b8c\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"d91cfe01\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 92. Consider a large vector Z, compute Z to the power of 3 using 3 different methods (★★★)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"b610d5b1\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"29645461\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 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? (★★★)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"9b8ceb78\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"687c2370\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 94. Considering a 10x3 matrix, extract rows with unequal values (e.g. [2,2,3]) (★★★)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"8455c06b\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"3726eeed\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 95. Convert a vector of ints into a matrix binary representation (★★★)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"cc0652d4\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"d31a4ffd\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 96. Given a two dimensional array, how to extract unique rows? (★★★)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"7a31971b\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"8b798880\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 97. Considering 2 vectors A & B, write the einsum equivalent of inner, outer, sum, and mul function (★★★)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"c8d2fc50\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"07655168\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 98. Considering a path described by two vectors (X,Y), how to sample it using equidistant samples (★★★)?\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"75b400ec\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"d9f463ce\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 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. (★★★)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"229d9f12\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"b019af39\",\n   \"metadata\": {},\n   \"source\": [\n    \"#### 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). (★★★)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"b86a6fce\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  }\n ],\n \"metadata\": {},\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"
  },
  {
    "path": "100_Numpy_exercises.md",
    "content": "\n\n\n# 100 numpy exercises\n\nThis is a collection of exercises that have been collected in the numpy mailing list, on stack overflow\nand in the numpy documentation. The goal of this collection is to offer a quick reference for both old\nand new users but also to provide a set of exercises for those who teach.\n\n\nIf you find an error or think you've a better way to solve some of them, feel\nfree to open an issue at <https://github.com/rougier/numpy-100>.\nFile automatically generated. See the documentation to update questions/answers/hints programmatically.\n\n#### 1. Import the numpy package under the name `np` (★☆☆)\n\n#### 2. Print the numpy version and the configuration (★☆☆)\n\n#### 3. Create a null vector of size 10 (★☆☆)\n\n#### 4. How to find the memory size of any array (★☆☆)\n\n#### 5. How to get the documentation of the numpy add function from the command line? (★☆☆)\n\n#### 6. Create a null vector of size 10 but the fifth value which is 1 (★☆☆)\n\n#### 7. Create a vector with values ranging from 10 to 49 (★☆☆)\n\n#### 8. Reverse a vector (first element becomes last) (★☆☆)\n\n#### 9. Create a 3x3 matrix with values ranging from 0 to 8 (★☆☆)\n\n#### 10. Find indices of non-zero elements from [1,2,0,0,4,0] (★☆☆)\n\n#### 11. Create a 3x3 identity matrix (★☆☆)\n\n#### 12. Create a 3x3x3 array with random values (★☆☆)\n\n#### 13. Create a 10x10 array with random values and find the minimum and maximum values (★☆☆)\n\n#### 14. Create a random vector of size 30 and find the mean value (★☆☆)\n\n#### 15. Create a 2d array with 1 on the border and 0 inside (★☆☆)\n\n#### 16. How to add a border (filled with 0's) around an existing array? (★☆☆)\n\n#### 17. What is the result of the following expression? (★☆☆)\n```python\n0 * np.nan\nnp.nan == np.nan\nnp.inf > np.nan\nnp.nan - np.nan\nnp.nan in set([np.nan])\n0.3 == 3 * 0.1\n```\n\n#### 18. Create a 5x5 matrix with values 1,2,3,4 just below the diagonal (★☆☆)\n\n#### 19. Create a 8x8 matrix and fill it with a checkerboard pattern (★☆☆)\n\n#### 20. Consider a (6,7,8) shape array, what is the index (x,y,z) of the 100th element? (★☆☆)\n\n#### 21. Create a checkerboard 8x8 matrix using the tile function (★☆☆)\n\n#### 22. Normalize a 5x5 random matrix (★☆☆)\n\n#### 23. Create a custom dtype that describes a color as four unsigned bytes (RGBA) (★☆☆)\n\n#### 24. Multiply a 5x3 matrix by a 3x2 matrix (real matrix product) (★☆☆)\n\n#### 25. Given a 1D array, negate all elements which are between 3 and 8, in place. (★☆☆)\n\n#### 26. What is the output of the following script? (★☆☆)\n```python\n# Author: Jake VanderPlas\n\nprint(sum(range(5),-1))\nfrom numpy import *\nprint(sum(range(5),-1))\n```\n\n#### 27. Consider an integer vector Z, which of these expressions are legal? (★☆☆)\n```python\nZ**Z\n2 << Z >> 2\nZ <- Z\n1j*Z\nZ/1/1\nZ<Z>Z\n```\n\n#### 28. What are the result of the following expressions? (★☆☆)\n```python\nnp.array(0) / np.array(0)\nnp.array(0) // np.array(0)\nnp.array([np.nan]).astype(int).astype(float)\n```\n\n#### 29. How to round away from zero a float array ? (★☆☆)\n\n#### 30. How to find common values between two arrays? (★☆☆)\n\n#### 31. How to ignore all numpy warnings (not recommended)? (★☆☆)\n\n#### 32. Is the following expressions true? (★☆☆)\n```python\nnp.sqrt(-1) == np.emath.sqrt(-1)\n```\n\n#### 33. How to get the dates of yesterday, today and tomorrow? (★☆☆)\n\n#### 34. How to get all the dates corresponding to the month of July 2016? (★★☆)\n\n#### 35. How to compute ((A+B)*(-A/2)) in place (without copy)? (★★☆)\n\n#### 36. Extract the integer part of a random array of positive numbers using 4 different methods (★★☆)\n\n#### 37. Create a 5x5 matrix with row values ranging from 0 to 4 (★★☆)\n\n#### 38. Consider a generator function that generates 10 integers and use it to build an array (★☆☆)\n\n#### 39. Create a vector of size 10 with values ranging from 0 to 1, both excluded (★★☆)\n\n#### 40. Create a random vector of size 10 and sort it (★★☆)\n\n#### 41. How to sum a small array faster than np.sum? (★★☆)\n\n#### 42. Consider two random arrays A and B, check if they are equal (★★☆)\n\n#### 43. Make an array immutable (read-only) (★★☆)\n\n#### 44. Consider a random 10x2 matrix representing cartesian coordinates, convert them to polar coordinates (★★☆)\n\n#### 45. Create random vector of size 10 and replace the maximum value by 0 (★★☆)\n\n#### 46. Create a structured array with `x` and `y` coordinates covering the [0,1]x[0,1] area (★★☆)\n\n#### 47. Given two arrays, X and Y, construct the Cauchy matrix C (Cij =1/(xi - yj)) (★★☆)\n\n#### 48. Print the minimum and maximum representable values for each numpy scalar type (★★☆)\n\n#### 49. How to print all the values of an array? (★★☆)\n\n#### 50. How to find the closest value (to a given scalar) in a vector? (★★☆)\n\n#### 51. Create a structured array representing a position (x,y) and a color (r,g,b) (★★☆)\n\n#### 52. Consider a random vector with shape (100,2) representing coordinates, find point by point distances (★★☆)\n\n#### 53. How to convert a float (32 bits) array into an integer (32 bits) array in place?\n\n#### 54. How to read the following file? (★★☆)\n```\n1, 2, 3, 4, 5\n6,  ,  , 7, 8\n ,  , 9,10,11\n```\n\n#### 55. What is the equivalent of enumerate for numpy arrays? (★★☆)\n\n#### 56. Generate a generic 2D Gaussian-like array (★★☆)\n\n#### 57. How to randomly place p elements in a 2D array? (★★☆)\n\n#### 58. Subtract the mean of each row of a matrix (★★☆)\n\n#### 59. How to sort an array by the nth column? (★★☆)\n\n#### 60. How to tell if a given 2D array has null columns? (★★☆)\n\n#### 61. Find the nearest value from a given value in an array (★★☆)\n\n#### 62. Considering two arrays with shape (1,3) and (3,1), how to compute their sum using an iterator? (★★☆)\n\n#### 63. Create an array class that has a name attribute (★★☆)\n\n#### 64. Consider a given vector, how to add 1 to each element indexed by a second vector (be careful with repeated indices)? (★★★)\n\n#### 65. How to accumulate elements of a vector (X) to an array (F) based on an index list (I)? (★★★)\n\n#### 66. Considering a (w,h,3) image of (dtype=ubyte), compute the number of unique colors (★★☆)\n\n#### 67. Considering a four dimensions array, how to get sum over the last two axis at once? (★★★)\n\n#### 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? (★★★)\n\n#### 69. How to get the diagonal of a dot product? (★★★)\n\n#### 70. Consider the vector [1, 2, 3, 4, 5], how to build a new vector with 3 consecutive zeros interleaved between each value? (★★★)\n\n#### 71. Consider an array of dimension (5,5,3), how to multiply it by an array with dimensions (5,5)? (★★★)\n\n#### 72. How to swap two rows of an array? (★★★)\n\n#### 73. Consider a set of 10 triplets describing 10 triangles (with shared vertices), find the set of unique line segments composing all the  triangles (★★★)\n\n#### 74. Given a sorted array C that corresponds to a bincount, how to produce an array A such that np.bincount(A) == C? (★★★)\n\n#### 75. How to compute averages using a sliding window over an array? (★★★)\n\n#### 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]) (★★★)\n\n#### 77. How to negate a boolean, or to change the sign of a float inplace? (★★★)\n\n#### 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])? (★★★)\n\n#### 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])? (★★★)\n\n#### 80. Consider an arbitrary array, write a function that extracts a subpart with a fixed shape and centered on a given element (pad with a `fill` value when necessary) (★★★)\n\n#### 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]]? (★★★)\n\n#### 82. Compute a matrix rank (★★★)\n\n#### 83. How to find the most frequent value in an array?\n\n#### 84. Extract all the contiguous 3x3 blocks from a random 10x10 matrix (★★★)\n\n#### 85. Create a 2D array subclass such that Z[i,j] == Z[j,i] (★★★)\n\n#### 86. Consider a set of p matrices with 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)) (★★★)\n\n#### 87. Consider a 16x16 array, how to get the block-sum (block size is 4x4)? (★★★)\n\n#### 88. How to implement the Game of Life using numpy arrays? (★★★)\n\n#### 89. How to get the n largest values of an array (★★★)\n\n#### 90. Given an arbitrary number of vectors, build the cartesian product (every combination of every item) (★★★)\n\n#### 91. How to create a record array from a regular array? (★★★)\n\n#### 92. Consider a large vector Z, compute Z to the power of 3 using 3 different methods (★★★)\n\n#### 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? (★★★)\n\n#### 94. Considering a 10x3 matrix, extract rows with unequal values (e.g. [2,2,3]) (★★★)\n\n#### 95. Convert a vector of ints into a matrix binary representation (★★★)\n\n#### 96. Given a two dimensional array, how to extract unique rows? (★★★)\n\n#### 97. Considering 2 vectors A & B, write the einsum equivalent of inner, outer, sum, and mul function (★★★)\n\n#### 98. Considering a path described by two vectors (X,Y), how to sample it using equidistant samples (★★★)?\n\n#### 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. (★★★)\n\n#### 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). (★★★)\n"
  },
  {
    "path": "100_Numpy_exercises_with_hints.md",
    "content": "\n\n\n# 100 numpy exercises\n\nThis is a collection of exercises that have been collected in the numpy mailing list, on stack overflow\nand in the numpy documentation. The goal of this collection is to offer a quick reference for both old\nand new users but also to provide a set of exercises for those who teach.\n\n\nIf you find an error or think you've a better way to solve some of them, feel\nfree to open an issue at <https://github.com/rougier/numpy-100>.\nFile automatically generated. See the documentation to update questions/answers/hints programmatically.\n\n#### 1. Import the numpy package under the name `np` (★☆☆)\n`hint: import … as`\n#### 2. Print the numpy version and the configuration (★☆☆)\n`hint: np.__version__, np.show_config)`\n#### 3. Create a null vector of size 10 (★☆☆)\n`hint: np.zeros`\n#### 4. How to find the memory size of any array (★☆☆)\n`hint: size, itemsize`\n#### 5. How to get the documentation of the numpy add function from the command line? (★☆☆)\n`hint: np.info`\n#### 6. Create a null vector of size 10 but the fifth value which is 1 (★☆☆)\n`hint: array[4]`\n#### 7. Create a vector with values ranging from 10 to 49 (★☆☆)\n`hint: arange`\n#### 8. Reverse a vector (first element becomes last) (★☆☆)\n`hint: array[::-1]`\n#### 9. Create a 3x3 matrix with values ranging from 0 to 8 (★☆☆)\n`hint: reshape`\n#### 10. Find indices of non-zero elements from [1,2,0,0,4,0] (★☆☆)\n`hint: np.nonzero`\n#### 11. Create a 3x3 identity matrix (★☆☆)\n`hint: np.eye`\n#### 12. Create a 3x3x3 array with random values (★☆☆)\n`hint: np.random.random`\n#### 13. Create a 10x10 array with random values and find the minimum and maximum values (★☆☆)\n`hint: min, max`\n#### 14. Create a random vector of size 30 and find the mean value (★☆☆)\n`hint: mean`\n#### 15. Create a 2d array with 1 on the border and 0 inside (★☆☆)\n`hint: array[1:-1, 1:-1]`\n#### 16. How to add a border (filled with 0's) around an existing array? (★☆☆)\n`hint: np.pad`\n#### 17. What is the result of the following expression? (★☆☆)\n```python\n0 * np.nan\nnp.nan == np.nan\nnp.inf > np.nan\nnp.nan - np.nan\nnp.nan in set([np.nan])\n0.3 == 3 * 0.1\n```\n`hint: NaN = not a number, inf = infinity`\n#### 18. Create a 5x5 matrix with values 1,2,3,4 just below the diagonal (★☆☆)\n`hint: np.diag`\n#### 19. Create a 8x8 matrix and fill it with a checkerboard pattern (★☆☆)\n`hint: array[::2]`\n#### 20. Consider a (6,7,8) shape array, what is the index (x,y,z) of the 100th element? (★☆☆)\n`hint: np.unravel_index`\n#### 21. Create a checkerboard 8x8 matrix using the tile function (★☆☆)\n`hint: np.tile`\n#### 22. Normalize a 5x5 random matrix (★☆☆)\n`hint: (x -mean)/std`\n#### 23. Create a custom dtype that describes a color as four unsigned bytes (RGBA) (★☆☆)\n`hint: np.dtype`\n#### 24. Multiply a 5x3 matrix by a 3x2 matrix (real matrix product) (★☆☆)\n`hint:`\n#### 25. Given a 1D array, negate all elements which are between 3 and 8, in place. (★☆☆)\n`hint: >, <`\n#### 26. What is the output of the following script? (★☆☆)\n```python\n# Author: Jake VanderPlas\n\nprint(sum(range(5),-1))\nfrom numpy import *\nprint(sum(range(5),-1))\n```\n`hint: np.sum`\n#### 27. Consider an integer vector Z, which of these expressions are legal? (★☆☆)\n```python\nZ**Z\n2 << Z >> 2\nZ <- Z\n1j*Z\nZ/1/1\nZ<Z>Z\n```\n`No hints provided...`\n#### 28. What are the result of the following expressions? (★☆☆)\n```python\nnp.array(0) / np.array(0)\nnp.array(0) // np.array(0)\nnp.array([np.nan]).astype(int).astype(float)\n```\n`No hints provided...`\n#### 29. How to round away from zero a float array ? (★☆☆)\n`hint: np.uniform, np.copysign, np.ceil, np.abs, np.where`\n#### 30. How to find common values between two arrays? (★☆☆)\n`hint: np.intersect1d`\n#### 31. How to ignore all numpy warnings (not recommended)? (★☆☆)\n`hint: np.seterr, np.errstate`\n#### 32. Is the following expressions true? (★☆☆)\n```python\nnp.sqrt(-1) == np.emath.sqrt(-1)\n```\n`hint: imaginary number`\n#### 33. How to get the dates of yesterday, today and tomorrow? (★☆☆)\n`hint: np.datetime64, np.timedelta64`\n#### 34. How to get all the dates corresponding to the month of July 2016? (★★☆)\n`hint: np.arange(dtype=datetime64['D'])`\n#### 35. How to compute ((A+B)*(-A/2)) in place (without copy)? (★★☆)\n`hint: np.add(out=), np.negative(out=), np.multiply(out=), np.divide(out=)`\n#### 36. Extract the integer part of a random array of positive numbers using 4 different methods (★★☆)\n`hint: %, np.floor, astype, np.trunc`\n#### 37. Create a 5x5 matrix with row values ranging from 0 to 4 (★★☆)\n`hint: np.arange`\n#### 38. Consider a generator function that generates 10 integers and use it to build an array (★☆☆)\n`hint: np.fromiter`\n#### 39. Create a vector of size 10 with values ranging from 0 to 1, both excluded (★★☆)\n`hint: np.linspace`\n#### 40. Create a random vector of size 10 and sort it (★★☆)\n`hint: sort`\n#### 41. How to sum a small array faster than np.sum? (★★☆)\n`hint: np.add.reduce`\n#### 42. Consider two random arrays A and B, check if they are equal (★★☆)\n`hint: np.allclose, np.array_equal`\n#### 43. Make an array immutable (read-only) (★★☆)\n`hint: flags.writeable`\n#### 44. Consider a random 10x2 matrix representing cartesian coordinates, convert them to polar coordinates (★★☆)\n`hint: np.sqrt, np.arctan2`\n#### 45. Create random vector of size 10 and replace the maximum value by 0 (★★☆)\n`hint: argmax`\n#### 46. Create a structured array with `x` and `y` coordinates covering the [0,1]x[0,1] area (★★☆)\n`hint: np.meshgrid`\n#### 47. Given two arrays, X and Y, construct the Cauchy matrix C (Cij =1/(xi - yj)) (★★☆)\n`hint: np.subtract.outer`\n#### 48. Print the minimum and maximum representable values for each numpy scalar type (★★☆)\n`hint: np.iinfo, np.finfo, eps`\n#### 49. How to print all the values of an array? (★★☆)\n`hint: np.set_printoptions`\n#### 50. How to find the closest value (to a given scalar) in a vector? (★★☆)\n`hint: argmin`\n#### 51. Create a structured array representing a position (x,y) and a color (r,g,b) (★★☆)\n`hint: dtype`\n#### 52. Consider a random vector with shape (100,2) representing coordinates, find point by point distances (★★☆)\n`hint: np.atleast_2d, T, np.sqrt`\n#### 53. How to convert a float (32 bits) array into an integer (32 bits) array in place?\n`hint: view and [:] =`\n#### 54. How to read the following file? (★★☆)\n```\n1, 2, 3, 4, 5\n6,  ,  , 7, 8\n ,  , 9,10,11\n```\n`hint: np.genfromtxt`\n#### 55. What is the equivalent of enumerate for numpy arrays? (★★☆)\n`hint: np.ndenumerate, np.ndindex`\n#### 56. Generate a generic 2D Gaussian-like array (★★☆)\n`hint: np.meshgrid, np.exp`\n#### 57. How to randomly place p elements in a 2D array? (★★☆)\n`hint: np.put, np.random.choice`\n#### 58. Subtract the mean of each row of a matrix (★★☆)\n`hint: mean(axis=,keepdims=)`\n#### 59. How to sort an array by the nth column? (★★☆)\n`hint: argsort`\n#### 60. How to tell if a given 2D array has null columns? (★★☆)\n`hint: any, ~`\n#### 61. Find the nearest value from a given value in an array (★★☆)\n`hint: np.abs, argmin, flat`\n#### 62. Considering two arrays with shape (1,3) and (3,1), how to compute their sum using an iterator? (★★☆)\n`hint: np.nditer`\n#### 63. Create an array class that has a name attribute (★★☆)\n`hint: class method`\n#### 64. Consider a given vector, how to add 1 to each element indexed by a second vector (be careful with repeated indices)? (★★★)\n`hint: np.bincount | np.add.at`\n#### 65. How to accumulate elements of a vector (X) to an array (F) based on an index list (I)? (★★★)\n`hint: np.bincount`\n#### 66. Considering a (w,h,3) image of (dtype=ubyte), compute the number of unique colors (★★☆)\n`hint: np.unique`\n#### 67. Considering a four dimensions array, how to get sum over the last two axis at once? (★★★)\n`hint: sum(axis=(-2,-1))`\n#### 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? (★★★)\n`hint: np.bincount`\n#### 69. How to get the diagonal of a dot product? (★★★)\n`hint: np.diag`\n#### 70. Consider the vector [1, 2, 3, 4, 5], how to build a new vector with 3 consecutive zeros interleaved between each value? (★★★)\n`hint: array[::4]`\n#### 71. Consider an array of dimension (5,5,3), how to multiply it by an array with dimensions (5,5)? (★★★)\n`hint: array[:, :, None]`\n#### 72. How to swap two rows of an array? (★★★)\n`hint: array[[]] = array[[]]`\n#### 73. Consider a set of 10 triplets describing 10 triangles (with shared vertices), find the set of unique line segments composing all the  triangles (★★★)\n`hint: repeat, np.roll, np.sort, view, np.unique`\n#### 74. Given a sorted array C that corresponds to a bincount, how to produce an array A such that np.bincount(A) == C? (★★★)\n`hint: np.repeat`\n#### 75. How to compute averages using a sliding window over an array? (★★★)\n`hint: np.cumsum, from numpy.lib.stride_tricks import sliding_window_view (np>=1.20.0)`\n#### 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]) (★★★)\n`hint: from numpy.lib import stride_tricks, from numpy.lib.stride_tricks import sliding_window_view (np>=1.20.0)`\n#### 77. How to negate a boolean, or to change the sign of a float inplace? (★★★)\n`hint: np.logical_not, np.negative`\n#### 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])? (★★★)\n`No hints provided...`\n#### 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])? (★★★)\n`No hints provided...`\n#### 80. Consider an arbitrary array, write a function that extracts a subpart with a fixed shape and centered on a given element (pad with a `fill` value when necessary) (★★★)\n`hint: minimum maximum`\n#### 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]]? (★★★)\n`hint: stride_tricks.as_strided, from numpy.lib.stride_tricks import sliding_window_view (np>=1.20.0)`\n#### 82. Compute a matrix rank (★★★)\n`hint: np.linalg.svd, np.linalg.matrix_rank`\n#### 83. How to find the most frequent value in an array?\n`hint: np.bincount, argmax`\n#### 84. Extract all the contiguous 3x3 blocks from a random 10x10 matrix (★★★)\n`hint: stride_tricks.as_strided, from numpy.lib.stride_tricks import sliding_window_view (np>=1.20.0)`\n#### 85. Create a 2D array subclass such that Z[i,j] == Z[j,i] (★★★)\n`hint: class method`\n#### 86. Consider a set of p matrices with 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)) (★★★)\n`hint: np.tensordot`\n#### 87. Consider a 16x16 array, how to get the block-sum (block size is 4x4)? (★★★)\n`hint: np.add.reduceat, from numpy.lib.stride_tricks import sliding_window_view (np>=1.20.0)`\n#### 88. How to implement the Game of Life using numpy arrays? (★★★)\n`No hints provided...`\n#### 89. How to get the n largest values of an array (★★★)\n`hint: np.argsort | np.argpartition`\n#### 90. Given an arbitrary number of vectors, build the cartesian product (every combination of every item) (★★★)\n`hint: np.indices`\n#### 91. How to create a record array from a regular array? (★★★)\n`hint: np.core.records.fromarrays`\n#### 92. Consider a large vector Z, compute Z to the power of 3 using 3 different methods (★★★)\n`hint: np.power, *, np.einsum`\n#### 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? (★★★)\n`hint: np.where`\n#### 94. Considering a 10x3 matrix, extract rows with unequal values (e.g. [2,2,3]) (★★★)\n`No hints provided...`\n#### 95. Convert a vector of ints into a matrix binary representation (★★★)\n`hint: np.unpackbits`\n#### 96. Given a two dimensional array, how to extract unique rows? (★★★)\n`hint: np.ascontiguousarray | np.unique`\n#### 97. Considering 2 vectors A & B, write the einsum equivalent of inner, outer, sum, and mul function (★★★)\n`hint: np.einsum`\n#### 98. Considering a path described by two vectors (X,Y), how to sample it using equidistant samples (★★★)?\n`hint: np.cumsum, np.interp`\n#### 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. (★★★)\n`hint: np.logical_and.reduce, np.mod`\n#### 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). (★★★)\n`hint: np.percentile`"
  },
  {
    "path": "100_Numpy_exercises_with_hints_with_solutions.md",
    "content": "\n\n\n# 100 numpy exercises\n\nThis is a collection of exercises that have been collected in the numpy mailing list, on stack overflow\nand in the numpy documentation. The goal of this collection is to offer a quick reference for both old\nand new users but also to provide a set of exercises for those who teach.\n\n\nIf you find an error or think you've a better way to solve some of them, feel\nfree to open an issue at <https://github.com/rougier/numpy-100>.\nFile automatically generated. See the documentation to update questions/answers/hints programmatically.\n\n#### 1. Import the numpy package under the name `np` (★☆☆)\n`hint: import … as`\n\n```python\nimport numpy as np\n```\n#### 2. Print the numpy version and the configuration (★☆☆)\n`hint: np.__version__, np.show_config)`\n\n```python\nprint(np.__version__)\nnp.show_config()\n```\n#### 3. Create a null vector of size 10 (★☆☆)\n`hint: np.zeros`\n\n```python\nZ = np.zeros(10)\nprint(Z)\n```\n#### 4. How to find the memory size of any array (★☆☆)\n`hint: size, itemsize`\n\n```python\nZ = np.zeros((10,10))\nprint(\"%d bytes\" % (Z.size * Z.itemsize))\n\n# Simpler alternative\nprint(\"%d bytes\" % Z.nbytes)\n```\n#### 5. How to get the documentation of the numpy add function from the command line? (★☆☆)\n`hint: np.info`\n\n```python\n%run `python -c \"import numpy; numpy.info(numpy.add)\"`\n```\n#### 6. Create a null vector of size 10 but the fifth value which is 1 (★☆☆)\n`hint: array[4]`\n\n```python\nZ = np.zeros(10)\nZ[4] = 1\nprint(Z)\n```\n#### 7. Create a vector with values ranging from 10 to 49 (★☆☆)\n`hint: arange`\n\n```python\nZ = np.arange(10,50)\nprint(Z)\n```\n#### 8. Reverse a vector (first element becomes last) (★☆☆)\n`hint: array[::-1]`\n\n```python\nZ = np.arange(50)\nZ = Z[::-1]\nprint(Z)\n```\n#### 9. Create a 3x3 matrix with values ranging from 0 to 8 (★☆☆)\n`hint: reshape`\n\n```python\nZ = np.arange(9).reshape(3, 3)\nprint(Z)\n```\n#### 10. Find indices of non-zero elements from [1,2,0,0,4,0] (★☆☆)\n`hint: np.nonzero`\n\n```python\nnz = np.nonzero([1,2,0,0,4,0])\nprint(nz)\n```\n#### 11. Create a 3x3 identity matrix (★☆☆)\n`hint: np.eye`\n\n```python\nZ = np.eye(3)\nprint(Z)\n```\n#### 12. Create a 3x3x3 array with random values (★☆☆)\n`hint: np.random.random`\n\n```python\nZ = np.random.random((3,3,3))\nprint(Z)\n```\n#### 13. Create a 10x10 array with random values and find the minimum and maximum values (★☆☆)\n`hint: min, max`\n\n```python\nZ = np.random.random((10,10))\nZmin, Zmax = Z.min(), Z.max()\nprint(Zmin, Zmax)\n```\n#### 14. Create a random vector of size 30 and find the mean value (★☆☆)\n`hint: mean`\n\n```python\nZ = np.random.random(30)\nm = Z.mean()\nprint(m)\n```\n#### 15. Create a 2d array with 1 on the border and 0 inside (★☆☆)\n`hint: array[1:-1, 1:-1]`\n\n```python\nZ = np.ones((10,10))\nZ[1:-1,1:-1] = 0\nprint(Z)\n```\n#### 16. How to add a border (filled with 0's) around an existing array? (★☆☆)\n`hint: np.pad`\n\n```python\nZ = np.ones((5,5))\nZ = np.pad(Z, pad_width=1, mode='constant', constant_values=0)\nprint(Z)\n\n# Not a solution to this problem but good to know: using fancy indexing for in-place edit\nZ[:, [0, -1]] = 0\nZ[[0, -1], :] = 0\nprint(Z)\n```\n#### 17. What is the result of the following expression? (★☆☆)\n```python\n0 * np.nan\nnp.nan == np.nan\nnp.inf > np.nan\nnp.nan - np.nan\nnp.nan in set([np.nan])\n0.3 == 3 * 0.1\n```\n`hint: NaN = not a number, inf = infinity`\n\n```python\nprint(0 * np.nan)\nprint(np.nan == np.nan)\nprint(np.inf > np.nan)\nprint(np.nan - np.nan)\nprint(np.nan in set([np.nan]))\nprint(0.3 == 3 * 0.1)\n```\n#### 18. Create a 5x5 matrix with values 1,2,3,4 just below the diagonal (★☆☆)\n`hint: np.diag`\n\n```python\nZ = np.diag(1+np.arange(4),k=-1)\nprint(Z)\n```\n#### 19. Create a 8x8 matrix and fill it with a checkerboard pattern (★☆☆)\n`hint: array[::2]`\n\n```python\nZ = np.zeros((8,8),dtype=int)\nZ[1::2,::2] = 1\nZ[::2,1::2] = 1\nprint(Z)\n```\n#### 20. Consider a (6,7,8) shape array, what is the index (x,y,z) of the 100th element? (★☆☆)\n`hint: np.unravel_index`\n\n```python\nprint(np.unravel_index(99,(6,7,8)))\n```\n#### 21. Create a checkerboard 8x8 matrix using the tile function (★☆☆)\n`hint: np.tile`\n\n```python\nZ = np.tile( np.array([[0,1],[1,0]]), (4,4))\nprint(Z)\n```\n#### 22. Normalize a 5x5 random matrix (★☆☆)\n`hint: (x -mean)/std`\n\n```python\nZ = np.random.random((5,5))\nZ = (Z - np.mean (Z)) / (np.std (Z))\nprint(Z)\n```\n#### 23. Create a custom dtype that describes a color as four unsigned bytes (RGBA) (★☆☆)\n`hint: np.dtype`\n\n```python\ncolor = np.dtype([(\"r\", np.ubyte),\n                  (\"g\", np.ubyte),\n                  (\"b\", np.ubyte),\n                  (\"a\", np.ubyte)])\n```\n#### 24. Multiply a 5x3 matrix by a 3x2 matrix (real matrix product) (★☆☆)\n`hint:`\n\n```python\nZ = np.matmul(np.ones((5, 3)), np.ones((3, 2)))\nprint(Z)\n\n# Alternative solution, in Python 3.5 and above\nZ = np.ones((5,3)) @ np.ones((3,2))\nprint(Z)\n```\n#### 25. Given a 1D array, negate all elements which are between 3 and 8, in place. (★☆☆)\n`hint: >, <`\n\n```python\n# Author: Evgeni Burovski\n\nZ = np.arange(11)\nZ[(3 < Z) & (Z < 8)] *= -1\nprint(Z)\n```\n#### 26. What is the output of the following script? (★☆☆)\n```python\n# Author: Jake VanderPlas\n\nprint(sum(range(5),-1))\nfrom numpy import *\nprint(sum(range(5),-1))\n```\n`hint: np.sum`\n\n```python\n# Author: Jake VanderPlas\n\nprint(sum(range(5),-1))\nfrom numpy import *\nprint(sum(range(5),-1))\n```\n#### 27. Consider an integer vector Z, which of these expressions are legal? (★☆☆)\n```python\nZ**Z\n2 << Z >> 2\nZ <- Z\n1j*Z\nZ/1/1\nZ<Z>Z\n```\n`No hints provided...`\n\n```python\nZ**Z\n2 << Z >> 2\nZ <- Z\n1j*Z\nZ/1/1\nZ<Z>Z\n```\n#### 28. What are the result of the following expressions? (★☆☆)\n```python\nnp.array(0) / np.array(0)\nnp.array(0) // np.array(0)\nnp.array([np.nan]).astype(int).astype(float)\n```\n`No hints provided...`\n\n```python\nprint(np.array(0) / np.array(0))\nprint(np.array(0) // np.array(0))\nprint(np.array([np.nan]).astype(int).astype(float))\n```\n#### 29. How to round away from zero a float array ? (★☆☆)\n`hint: np.uniform, np.copysign, np.ceil, np.abs, np.where`\n\n```python\n# Author: Charles R Harris\n\nZ = np.random.uniform(-10,+10,10)\nprint(np.copysign(np.ceil(np.abs(Z)), Z))\n\n# More readable but less efficient\nprint(np.where(Z>0, np.ceil(Z), np.floor(Z)))\n```\n#### 30. How to find common values between two arrays? (★☆☆)\n`hint: np.intersect1d`\n\n```python\nZ1 = np.random.randint(0,10,10)\nZ2 = np.random.randint(0,10,10)\nprint(np.intersect1d(Z1,Z2))\n```\n#### 31. How to ignore all numpy warnings (not recommended)? (★☆☆)\n`hint: np.seterr, np.errstate`\n\n```python\n# Suicide mode on\ndefaults = np.seterr(all=\"ignore\")\nZ = np.ones(1) / 0\n\n# Back to sanity\n_ = np.seterr(**defaults)\n\n# Equivalently with a context manager\nwith np.errstate(all=\"ignore\"):\n    np.arange(3) / 0\n```\n#### 32. Is the following expressions true? (★☆☆)\n```python\nnp.sqrt(-1) == np.emath.sqrt(-1)\n```\n`hint: imaginary number`\n\n```python\nnp.sqrt(-1) == np.emath.sqrt(-1)\n```\n#### 33. How to get the dates of yesterday, today and tomorrow? (★☆☆)\n`hint: np.datetime64, np.timedelta64`\n\n```python\nyesterday = np.datetime64('today') - np.timedelta64(1)\ntoday     = np.datetime64('today')\ntomorrow  = np.datetime64('today') + np.timedelta64(1)\n```\n#### 34. How to get all the dates corresponding to the month of July 2016? (★★☆)\n`hint: np.arange(dtype=datetime64['D'])`\n\n```python\nZ = np.arange('2016-07', '2016-08', dtype='datetime64[D]')\nprint(Z)\n```\n#### 35. How to compute ((A+B)*(-A/2)) in place (without copy)? (★★☆)\n`hint: np.add(out=), np.negative(out=), np.multiply(out=), np.divide(out=)`\n\n```python\nA = np.ones(3)*1\nB = np.ones(3)*2\nnp.add(A,B,out=B)\nnp.divide(A,2,out=A)\nnp.negative(A,out=A)\nnp.multiply(A,B,out=A)\n```\n#### 36. Extract the integer part of a random array of positive numbers using 4 different methods (★★☆)\n`hint: %, np.floor, astype, np.trunc`\n\n```python\nZ = np.random.uniform(0,10,10)\n\nprint(Z - Z%1)\nprint(Z // 1)\nprint(np.floor(Z))\nprint(Z.astype(int))\nprint(np.trunc(Z))\n```\n#### 37. Create a 5x5 matrix with row values ranging from 0 to 4 (★★☆)\n`hint: np.arange`\n\n```python\nZ = np.zeros((5,5))\nZ += np.arange(5)\nprint(Z)\n\n# without broadcasting\nZ = np.tile(np.arange(0, 5), (5,1))\nprint(Z)\n```\n#### 38. Consider a generator function that generates 10 integers and use it to build an array (★☆☆)\n`hint: np.fromiter`\n\n```python\ndef generate():\n    for x in range(10):\n        yield x\nZ = np.fromiter(generate(),dtype=float,count=-1)\nprint(Z)\n```\n#### 39. Create a vector of size 10 with values ranging from 0 to 1, both excluded (★★☆)\n`hint: np.linspace`\n\n```python\nZ = np.linspace(0,1,11,endpoint=False)[1:]\nprint(Z)\n```\n#### 40. Create a random vector of size 10 and sort it (★★☆)\n`hint: sort`\n\n```python\nZ = np.random.random(10)\nZ.sort()\nprint(Z)\n```\n#### 41. How to sum a small array faster than np.sum? (★★☆)\n`hint: np.add.reduce`\n\n```python\n# Author: Evgeni Burovski\n\nZ = np.arange(10)\nnp.add.reduce(Z)\n```\n#### 42. Consider two random arrays A and B, check if they are equal (★★☆)\n`hint: np.allclose, np.array_equal`\n\n```python\nA = np.random.randint(0,2,5)\nB = np.random.randint(0,2,5)\n\n# Assuming identical shape of the arrays and a tolerance for the comparison of values\nequal = np.allclose(A,B)\nprint(equal)\n\n# Checking both the shape and the element values, no tolerance (values have to be exactly equal)\nequal = np.array_equal(A,B)\nprint(equal)\n```\n#### 43. Make an array immutable (read-only) (★★☆)\n`hint: flags.writeable`\n\n```python\nZ = np.zeros(10)\nZ.flags.writeable = False\nZ[0] = 1\n```\n#### 44. Consider a random 10x2 matrix representing cartesian coordinates, convert them to polar coordinates (★★☆)\n`hint: np.sqrt, np.arctan2`\n\n```python\nZ = np.random.random((10,2))\nX,Y = Z[:,0], Z[:,1]\nR = np.sqrt(X**2+Y**2)\nT = np.arctan2(Y,X)\nprint(R)\nprint(T)\n```\n#### 45. Create random vector of size 10 and replace the maximum value by 0 (★★☆)\n`hint: argmax`\n\n```python\nZ = np.random.random(10)\nZ[Z.argmax()] = 0\nprint(Z)\n```\n#### 46. Create a structured array with `x` and `y` coordinates covering the [0,1]x[0,1] area (★★☆)\n`hint: np.meshgrid`\n\n```python\nZ = np.zeros((5,5), [('x',float),('y',float)])\nZ['x'], Z['y'] = np.meshgrid(np.linspace(0,1,5),\n                             np.linspace(0,1,5))\nprint(Z)\n```\n#### 47. Given two arrays, X and Y, construct the Cauchy matrix C (Cij =1/(xi - yj)) (★★☆)\n`hint: np.subtract.outer`\n\n```python\n# Author: Evgeni Burovski\n\nX = np.arange(8)\nY = X + 0.5\nC = 1.0 / np.subtract.outer(X, Y)\nprint(np.linalg.det(C))\n```\n#### 48. Print the minimum and maximum representable values for each numpy scalar type (★★☆)\n`hint: np.iinfo, np.finfo, eps`\n\n```python\nfor dtype in [np.int8, np.int32, np.int64]:\n   print(np.iinfo(dtype).min)\n   print(np.iinfo(dtype).max)\nfor dtype in [np.float32, np.float64]:\n   print(np.finfo(dtype).min)\n   print(np.finfo(dtype).max)\n   print(np.finfo(dtype).eps)\n```\n#### 49. How to print all the values of an array? (★★☆)\n`hint: np.set_printoptions`\n\n```python\nnp.set_printoptions(threshold=float(\"inf\"))\nZ = np.zeros((40,40))\nprint(Z)\n```\n#### 50. How to find the closest value (to a given scalar) in a vector? (★★☆)\n`hint: argmin`\n\n```python\nZ = np.arange(100)\nv = np.random.uniform(0,100)\nindex = (np.abs(Z-v)).argmin()\nprint(Z[index])\n```\n#### 51. Create a structured array representing a position (x,y) and a color (r,g,b) (★★☆)\n`hint: dtype`\n\n```python\nZ = np.zeros(10, [ ('position', [ ('x', float, 1),\n                                  ('y', float, 1)]),\n                   ('color',    [ ('r', float, 1),\n                                  ('g', float, 1),\n                                  ('b', float, 1)])])\nprint(Z)\n```\n#### 52. Consider a random vector with shape (100,2) representing coordinates, find point by point distances (★★☆)\n`hint: np.atleast_2d, T, np.sqrt`\n\n```python\nZ = np.random.random((10,2))\nX,Y = np.atleast_2d(Z[:,0], Z[:,1])\nD = np.sqrt( (X-X.T)**2 + (Y-Y.T)**2)\nprint(D)\n\n# Much faster with scipy\nimport scipy\n# Thanks Gavin Heverly-Coulson (#issue 1)\nimport scipy.spatial\n\nZ = np.random.random((10,2))\nD = scipy.spatial.distance.cdist(Z,Z)\nprint(D)\n```\n#### 53. How to convert a float (32 bits) array into an integer (32 bits) array in place?\n`hint: view and [:] =`\n\n```python\n# Thanks Vikas (https://stackoverflow.com/a/10622758/5989906)\n# & unutbu (https://stackoverflow.com/a/4396247/5989906)\nZ = (np.random.rand(10)*100).astype(np.float32)\nY = Z.view(np.int32)\nY[:] = Z\nprint(Y)\n```\n#### 54. How to read the following file? (★★☆)\n```\n1, 2, 3, 4, 5\n6,  ,  , 7, 8\n ,  , 9,10,11\n```\n`hint: np.genfromtxt`\n\n```python\nfrom io import StringIO\n\n# Fake file\ns = StringIO('''1, 2, 3, 4, 5\n\n                6,  ,  , 7, 8\n\n                 ,  , 9,10,11\n''')\nZ = np.genfromtxt(s, delimiter=\",\", dtype = int, filling_values = 0)\nprint(Z)\n```\n#### 55. What is the equivalent of enumerate for numpy arrays? (★★☆)\n`hint: np.ndenumerate, np.ndindex`\n\n```python\nZ = np.arange(9).reshape(3,3)\nfor index, value in np.ndenumerate(Z):\n    print(index, value)\nfor index in np.ndindex(Z.shape):\n    print(index, Z[index])\n```\n#### 56. Generate a generic 2D Gaussian-like array (★★☆)\n`hint: np.meshgrid, np.exp`\n\n```python\nX, Y = np.meshgrid(np.linspace(-1,1,10), np.linspace(-1,1,10))\nD = np.sqrt(X*X+Y*Y)\nsigma, mu = 1.0, 0.0\nG = np.exp(-( (D-mu)**2 / ( 2.0 * sigma**2 ) ) )\nprint(G)\n```\n#### 57. How to randomly place p elements in a 2D array? (★★☆)\n`hint: np.put, np.random.choice`\n\n```python\n# Author: Divakar\n\nn = 10\np = 3\nZ = np.zeros((n,n))\nnp.put(Z, np.random.choice(range(n*n), p, replace=False),1)\nprint(Z)\n```\n#### 58. Subtract the mean of each row of a matrix (★★☆)\n`hint: mean(axis=,keepdims=)`\n\n```python\n# Author: Warren Weckesser\n\nX = np.random.rand(5, 10)\n\n# Recent versions of numpy\nY = X - X.mean(axis=1, keepdims=True)\n\n# Older versions of numpy\nY = X - X.mean(axis=1).reshape(-1, 1)\n\nprint(Y)\n```\n#### 59. How to sort an array by the nth column? (★★☆)\n`hint: argsort`\n\n```python\n# Author: Steve Tjoa\n\nZ = np.random.randint(0,10,(3,3))\nprint(Z)\nprint(Z[Z[:,1].argsort()])\n```\n#### 60. How to tell if a given 2D array has null columns? (★★☆)\n`hint: any, ~`\n\n```python\n# Author: Warren Weckesser\n\n# null : 0 \nZ = np.random.randint(0,3,(3,10))\nprint((~Z.any(axis=0)).any())\n\n# null : np.nan\nZ=np.array([\n    [0,1,np.nan],\n    [1,2,np.nan],\n    [4,5,np.nan]\n])\nprint(np.isnan(Z).all(axis=0))\n```\n#### 61. Find the nearest value from a given value in an array (★★☆)\n`hint: np.abs, argmin, flat`\n\n```python\nZ = np.random.uniform(0,1,10)\nz = 0.5\nm = Z.flat[np.abs(Z - z).argmin()]\nprint(m)\n```\n#### 62. Considering two arrays with shape (1,3) and (3,1), how to compute their sum using an iterator? (★★☆)\n`hint: np.nditer`\n\n```python\nA = np.arange(3).reshape(3,1)\nB = np.arange(3).reshape(1,3)\nit = np.nditer([A,B,None])\nfor x,y,z in it: z[...] = x + y\nprint(it.operands[2])\n```\n#### 63. Create an array class that has a name attribute (★★☆)\n`hint: class method`\n\n```python\nclass 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.name = getattr(obj, 'name', \"no name\")\n\nZ = NamedArray(np.arange(10), \"range_10\")\nprint (Z.name)\n```\n#### 64. Consider a given vector, how to add 1 to each element indexed by a second vector (be careful with repeated indices)? (★★★)\n`hint: np.bincount | np.add.at`\n\n```python\n# Author: Brett Olsen\n\nZ = np.ones(10)\nI = np.random.randint(0,len(Z),20)\nZ += np.bincount(I, minlength=len(Z))\nprint(Z)\n\n# Another solution\n# Author: Bartosz Telenczuk\nnp.add.at(Z, I, 1)\nprint(Z)\n```\n#### 65. How to accumulate elements of a vector (X) to an array (F) based on an index list (I)? (★★★)\n`hint: np.bincount`\n\n```python\n# Author: Alan G Isaac\n\nX = [1,2,3,4,5,6]\nI = [1,3,9,3,4,1]\nF = np.bincount(I,X)\nprint(F)\n```\n#### 66. Considering a (w,h,3) image of (dtype=ubyte), compute the number of unique colors (★★☆)\n`hint: np.unique`\n\n```python\n# Author: Fisher Wang\n\nw, h = 256, 256\nI = np.random.randint(0, 4, (h, w, 3)).astype(np.ubyte)\ncolors = np.unique(I.reshape(-1, 3), axis=0)\nn = len(colors)\nprint(n)\n\n# Faster version\n# Author: Mark Setchell\n# https://stackoverflow.com/a/59671950/2836621\n\nw, h = 256, 256\nI = np.random.randint(0,4,(h,w,3), dtype=np.uint8)\n\n# View each pixel as a single 24-bit integer, rather than three 8-bit bytes\nI24 = np.dot(I.astype(np.uint32),[1,256,65536])\n\n# Count unique colours\nn = len(np.unique(I24))\nprint(n)\n```\n#### 67. Considering a four dimensions array, how to get sum over the last two axis at once? (★★★)\n`hint: sum(axis=(-2,-1))`\n\n```python\nA = np.random.randint(0,10,(3,4,3,4))\n# solution by passing a tuple of axes (introduced in numpy 1.7.0)\nsum = A.sum(axis=(-2,-1))\nprint(sum)\n# solution by flattening the last two dimensions into one\n# (useful for functions that don't accept tuples for axis argument)\nsum = A.reshape(A.shape[:-2] + (-1,)).sum(axis=-1)\nprint(sum)\n```\n#### 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? (★★★)\n`hint: np.bincount`\n\n```python\n# Author: Jaime Fernández del Río\n\nD = np.random.uniform(0,1,100)\nS = np.random.randint(0,10,100)\nD_sums = np.bincount(S, weights=D)\nD_counts = np.bincount(S)\nD_means = D_sums / D_counts\nprint(D_means)\n\n# Pandas solution as a reference due to more intuitive code\nimport pandas as pd\nprint(pd.Series(D).groupby(S).mean())\n```\n#### 69. How to get the diagonal of a dot product? (★★★)\n`hint: np.diag`\n\n```python\n# Author: Mathieu Blondel\n\nA = np.random.uniform(0,1,(5,5))\nB = np.random.uniform(0,1,(5,5))\n\n# Slow version\nnp.diag(np.dot(A, B))\n\n# Fast version\nnp.sum(A * B.T, axis=1)\n\n# Faster version\nnp.einsum(\"ij,ji->i\", A, B)\n```\n#### 70. Consider the vector [1, 2, 3, 4, 5], how to build a new vector with 3 consecutive zeros interleaved between each value? (★★★)\n`hint: array[::4]`\n\n```python\n# Author: Warren Weckesser\n\nZ = np.array([1,2,3,4,5])\nnz = 3\nZ0 = np.zeros(len(Z) + (len(Z)-1)*(nz))\nZ0[::nz+1] = Z\nprint(Z0)\n```\n#### 71. Consider an array of dimension (5,5,3), how to multiply it by an array with dimensions (5,5)? (★★★)\n`hint: array[:, :, None]`\n\n```python\nA = np.ones((5,5,3))\nB = 2*np.ones((5,5))\nprint(A * B[:,:,None])\n```\n#### 72. How to swap two rows of an array? (★★★)\n`hint: array[[]] = array[[]]`\n\n```python\n# Author: Eelco Hoogendoorn\n\nA = np.arange(25).reshape(5,5)\nA[[0,1]] = A[[1,0]]\nprint(A)\n```\n#### 73. Consider a set of 10 triplets describing 10 triangles (with shared vertices), find the set of unique line segments composing all the  triangles (★★★)\n`hint: repeat, np.roll, np.sort, view, np.unique`\n\n```python\n# Author: Nicolas P. Rougier\n\nfaces = np.random.randint(0,100,(10,3))\nF = np.roll(faces.repeat(2,axis=1),-1,axis=1)\nF = F.reshape(len(F)*3,2)\nF = np.sort(F,axis=1)\nG = F.view( dtype=[('p0',F.dtype),('p1',F.dtype)] )\nG = np.unique(G)\nprint(G)\n```\n#### 74. Given a sorted array C that corresponds to a bincount, how to produce an array A such that np.bincount(A) == C? (★★★)\n`hint: np.repeat`\n\n```python\n# Author: Jaime Fernández del Río\n\nC = np.bincount([1,1,2,3,4,4,6])\nA = np.repeat(np.arange(len(C)), C)\nprint(A)\n```\n#### 75. How to compute averages using a sliding window over an array? (★★★)\n`hint: np.cumsum, from numpy.lib.stride_tricks import sliding_window_view (np>=1.20.0)`\n\n```python\n# Author: Jaime Fernández del Río\n\ndef 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\nZ = np.arange(20)\nprint(moving_average(Z, n=3))\n\n# Author: Jeff Luo (@Jeff1999)\n# make sure your NumPy >= 1.20.0\n\nfrom numpy.lib.stride_tricks import sliding_window_view\n\nZ = np.arange(20)\nprint(sliding_window_view(Z, window_shape=3).mean(axis=-1))\n```\n#### 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]) (★★★)\n`hint: from numpy.lib import stride_tricks, from numpy.lib.stride_tricks import sliding_window_view (np>=1.20.0)`\n\n```python\n# Author: Joe Kington / Erik Rigtorp\nfrom numpy.lib import stride_tricks\n\ndef rolling(a, window):\n    shape = (a.size - window + 1, window)\n    strides = (a.strides[0], a.strides[0])\n    return stride_tricks.as_strided(a, shape=shape, strides=strides)\nZ = rolling(np.arange(10), 3)\nprint(Z)\n\n# Author: Jeff Luo (@Jeff1999)\n\nZ = np.arange(10)\nprint(sliding_window_view(Z, window_shape=3))\n```\n#### 77. How to negate a boolean, or to change the sign of a float inplace? (★★★)\n`hint: np.logical_not, np.negative`\n\n```python\n# Author: Nathaniel J. Smith\n\nZ = np.random.randint(0,2,100)\nnp.logical_not(Z, out=Z)\n\nZ = np.random.uniform(-1.0,1.0,100)\nnp.negative(Z, out=Z)\n```\n#### 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])? (★★★)\n`No hints provided...`\n\n```python\nP0 = np.random.uniform(-10,10,(10,2))\nP1 = np.random.uniform(-10,10,(10,2))\np  = np.random.uniform(-10,10,( 1,2))\n\ndef distance_faster(P0,P1,p):\n    #Author: Hemanth Pasupuleti\n    #Reference: https://mathworld.wolfram.com/Point-LineDistance2-Dimensional.html\n\n    v = P1- P0 \n    v[:,[0,1]] = v[:,[1,0]]\n    v[:,1]*=-1 \n    norm = np.linalg.norm(v,axis=1)   \n    r = P0 - p\n    d = np.abs(np.einsum(\"ij,ij->i\",r,v)) / norm \n\n    return d\n\nprint(distance_faster(P0, P1, p))\n\n##--------------- OR ---------------##\ndef distance_slower(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\nprint(distance_slower(P0, P1, p))\n```\n#### 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])? (★★★)\n`No hints provided...`\n\n```python\n# Author: Italmassov Kuanysh\n\n# based on distance function from previous question\nP0 = np.random.uniform(-10, 10, (10,2))\nP1 = np.random.uniform(-10,10,(10,2))\np = np.random.uniform(-10, 10, (10,2))\nprint(np.array([distance(P0,P1,p_i) for p_i in p]))\n\n# Author: Yang Wu (Broadcasting)\ndef distance_points_to_lines(p: np.ndarray, p_1: np.ndarray, p_2: np.ndarray) -> np.ndarray:\n    x_0, y_0 = p.T  # Shape -> (n points, )\n    x_1, y_1 = p_1.T  # Shape -> (n lines, )\n    x_2, y_2 = p_2.T  # Shape -> (n lines, )\n\n    # Displacement vector coordinates from p_1 -> p_2\n    dx = x_2 - x_1  # Shape -> (n lines, )\n    dy = y_2 - y_1  # Shape -> (n lines, )\n\n    # The 'cross product' term\n    cross_term = x_2 * y_1 - y_2 * x_1  # Shape -> (n lines, )\n\n    # Broadcast x_0, y_0 (n points, 1) and dx, dy, cross_term (1, n lines) -> (n points, n lines)\n    numerator = np.abs(\n        dy[np.newaxis, :] * x_0[:, np.newaxis]\n        - dx[np.newaxis, :] * y_0[:, np.newaxis]\n        + cross_term[np.newaxis, :]\n    )\n    denominator = np.sqrt(dx**2 + dy**2)  # Shape -> (n lines, )\n\n    # Shape (n points, n lines) / (1, n_lines) -> (n points, n lines)\n    return numerator / denominator[np.newaxis, :]\n\ndistance_points_to_lines(p, P0, P1)\n```\n#### 80. Consider an arbitrary array, write a function that extracts a subpart with a fixed shape and centered on a given element (pad with a `fill` value when necessary) (★★★)\n`hint: minimum maximum`\n\n```python\n# Author: Nicolas Rougier\n\nZ = np.random.randint(0,10,(10,10))\nshape = (5,5)\nfill  = 0\nposition = (1,1)\n\nR = np.ones(shape, dtype=Z.dtype)*fill\nP  = np.array(list(position)).astype(int)\nRs = np.array(list(R.shape)).astype(int)\nZs = np.array(list(Z.shape)).astype(int)\n\nR_start = np.zeros((len(shape),)).astype(int)\nR_stop  = np.array(list(shape)).astype(int)\nZ_start = (P-Rs//2)\nZ_stop  = (P+Rs//2)+Rs%2\n\nR_start = (R_start - np.minimum(Z_start,0)).tolist()\nZ_start = (np.maximum(Z_start,0)).tolist()\nR_stop = np.maximum(R_start, (R_stop - np.maximum(Z_stop-Zs,0))).tolist()\nZ_stop = (np.minimum(Z_stop,Zs)).tolist()\n\nr = tuple([slice(start,stop) for start,stop in zip(R_start,R_stop)])\nz = tuple([slice(start,stop) for start,stop in zip(Z_start,Z_stop)])\nR[r] = Z[z]\nprint(Z)\nprint(R)\n```\n#### 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]]? (★★★)\n`hint: stride_tricks.as_strided, from numpy.lib.stride_tricks import sliding_window_view (np>=1.20.0)`\n\n```python\n# Author: Stefan van der Walt\n\nZ = np.arange(1,15,dtype=np.uint32)\nR = stride_tricks.as_strided(Z,(11,4),(4,4))\nprint(R)\n\n# Author: Jeff Luo (@Jeff1999)\n\nZ = np.arange(1, 15, dtype=np.uint32)\nprint(sliding_window_view(Z, window_shape=4))\n```\n#### 82. Compute a matrix rank (★★★)\n`hint: np.linalg.svd, np.linalg.matrix_rank`\n\n```python\n# Author: Stefan van der Walt\n\nZ = np.random.uniform(0,1,(10,10))\nU, S, V = np.linalg.svd(Z) # Singular Value Decomposition\nthreshold = len(S) * S.max() * np.finfo(S.dtype).eps\nrank = np.sum(S > threshold)\nprint(rank)\n\n# alternative solution:\n# Author: Jeff Luo (@Jeff1999)\n\nrank = np.linalg.matrix_rank(Z)\nprint(rank)\n```\n#### 83. How to find the most frequent value in an array?\n`hint: np.bincount, argmax`\n\n```python\nZ = np.random.randint(0,10,50)\nprint(np.bincount(Z).argmax())\n```\n#### 84. Extract all the contiguous 3x3 blocks from a random 10x10 matrix (★★★)\n`hint: stride_tricks.as_strided, from numpy.lib.stride_tricks import sliding_window_view (np>=1.20.0)`\n\n```python\n# Author: Chris Barker\n\nZ = np.random.randint(0,5,(10,10))\nn = 3\ni = 1 + (Z.shape[0]-3)\nj = 1 + (Z.shape[1]-3)\nC = stride_tricks.as_strided(Z, shape=(i, j, n, n), strides=Z.strides + Z.strides)\nprint(C)\n\n# Author: Jeff Luo (@Jeff1999)\n\nZ = np.random.randint(0,5,(10,10))\nprint(sliding_window_view(Z, window_shape=(3, 3)))\n```\n#### 85. Create a 2D array subclass such that Z[i,j] == Z[j,i] (★★★)\n`hint: class method`\n\n```python\n# Author: Eric O. Lebigot\n# Note: only works for 2d array and value setting using indices\n\nclass 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\ndef symetric(Z):\n    return np.asarray(Z + Z.T - np.diag(Z.diagonal())).view(Symetric)\n\nS = symetric(np.random.randint(0,10,(5,5)))\nS[2,3] = 42\nprint(S)\n```\n#### 86. Consider a set of p matrices with 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)) (★★★)\n`hint: np.tensordot`\n\n```python\n# Author: Stefan van der Walt\n\np, n = 10, 20\nM = np.ones((p,n,n))\nV = np.ones((p,n,1))\nS = np.tensordot(M, V, axes=[[0, 2], [0, 1]])\nprint(S)\n\n# It works, because:\n# M is (p,n,n)\n# V is (p,n,1)\n# Thus, summing over the paired axes 0 and 0 (of M and V independently),\n# and 2 and 1, to remain with a (n,1) vector.\n```\n#### 87. Consider a 16x16 array, how to get the block-sum (block size is 4x4)? (★★★)\n`hint: np.add.reduceat, from numpy.lib.stride_tricks import sliding_window_view (np>=1.20.0)`\n\n```python\n# Author: Robert Kern\n\nZ = np.ones((16,16))\nk = 4\nS = 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)\nprint(S)\n\n# alternative solution:\n# Author: Sebastian Wallkötter (@FirefoxMetzger)\n\nZ = np.ones((16,16))\nk = 4\n\nwindows = np.lib.stride_tricks.sliding_window_view(Z, (k, k))\nS = windows[::k, ::k, ...].sum(axis=(-2, -1))\n\n# alternative solution (by @Gattocrucco)\nS = Z.reshape(4, 4, 4, 4).sum((1, 3))\n```\n#### 88. How to implement the Game of Life using numpy arrays? (★★★)\n`No hints provided...`\n\n```python\n# Author: Nicolas Rougier\n\ndef 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\nZ = np.random.randint(0,2,(50,50))\nfor i in range(100): Z = iterate(Z)\nprint(Z)\n```\n#### 89. How to get the n largest values of an array (★★★)\n`hint: np.argsort | np.argpartition`\n\n```python\nZ = np.arange(10000)\nnp.random.shuffle(Z)\nn = 5\n\n# Slow\nprint (Z[np.argsort(Z)[-n:]])\n\n# Fast\nprint (Z[np.argpartition(-Z,n)[:n]])\n```\n#### 90. Given an arbitrary number of vectors, build the cartesian product (every combination of every item) (★★★)\n`hint: np.indices`\n\n```python\n# Author: Stefan Van der Walt\n\ndef 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\nprint (cartesian(([1, 2, 3], [4, 5], [6, 7])))\n```\n#### 91. How to create a record array from a regular array? (★★★)\n`hint: np.core.records.fromarrays`\n\n```python\nZ = np.array([(\"Hello\", 2.5, 3),\n              (\"World\", 3.6, 2)])\nR = np.core.records.fromarrays(Z.T,\n                               names='col1, col2, col3',\n                               formats = 'S8, f8, i8')\nprint(R)\n```\n#### 92. Consider a large vector Z, compute Z to the power of 3 using 3 different methods (★★★)\n`hint: np.power, *, np.einsum`\n\n```python\n# Author: Ryan G.\n\nx = np.random.rand(int(5e7))\n\n%timeit np.power(x,3)\n%timeit x*x*x\n%timeit np.einsum('i,i,i->i',x,x,x)\n```\n#### 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? (★★★)\n`hint: np.where`\n\n```python\n# Author: Gabe Schwartz\n\nA = np.random.randint(0,5,(8,3))\nB = np.random.randint(0,5,(2,2))\n\nC = (A[..., np.newaxis, np.newaxis] == B)\nrows = np.where(C.any((3,1)).all(1))[0]\nprint(rows)\n```\n#### 94. Considering a 10x3 matrix, extract rows with unequal values (e.g. [2,2,3]) (★★★)\n`No hints provided...`\n\n```python\n# Author: Robert Kern\n\nZ = np.random.randint(0,5,(10,3))\nprint(Z)\n# solution for arrays of all dtypes (including string arrays and record arrays)\nE = np.all(Z[:,1:] == Z[:,:-1], axis=1)\nU = Z[~E]\nprint(U)\n# soluiton for numerical arrays only, will work for any number of columns in Z\nU = Z[Z.max(axis=1) != Z.min(axis=1),:]\nprint(U)\n```\n#### 95. Convert a vector of ints into a matrix binary representation (★★★)\n`hint: np.unpackbits`\n\n```python\n# Author: Warren Weckesser\n\nI = np.array([0, 1, 2, 3, 15, 16, 32, 64, 128])\nB = ((I.reshape(-1,1) & (2**np.arange(8))) != 0).astype(int)\nprint(B[:,::-1])\n\n# Author: Daniel T. McDonald\n\nI = np.array([0, 1, 2, 3, 15, 16, 32, 64, 128], dtype=np.uint8)\nprint(np.unpackbits(I[:, np.newaxis], axis=1))\n```\n#### 96. Given a two dimensional array, how to extract unique rows? (★★★)\n`hint: np.ascontiguousarray | np.unique`\n\n```python\n# Author: Jaime Fernández del Río\n\nZ = np.random.randint(0,2,(6,3))\nT = np.ascontiguousarray(Z).view(np.dtype((np.void, Z.dtype.itemsize * Z.shape[1])))\n_, idx = np.unique(T, return_index=True)\nuZ = Z[idx]\nprint(uZ)\n\n# Author: Andreas Kouzelis\n# NumPy >= 1.13\nuZ = np.unique(Z, axis=0)\nprint(uZ)\n```\n#### 97. Considering 2 vectors A & B, write the einsum equivalent of inner, outer, sum, and mul function (★★★)\n`hint: np.einsum`\n\n```python\n# Author: Alex Riley\n# Make sure to read: http://ajcr.net/Basic-guide-to-einsum/\n\nA = np.random.uniform(0,1,10)\nB = np.random.uniform(0,1,10)\n\nnp.einsum('i->', A)       # np.sum(A)\nnp.einsum('i,i->i', A, B) # A * B\nnp.einsum('i,i', A, B)    # np.inner(A, B)\nnp.einsum('i,j->ij', A, B)    # np.outer(A, B)\n```\n#### 98. Considering a path described by two vectors (X,Y), how to sample it using equidistant samples (★★★)?\n`hint: np.cumsum, np.interp`\n\n```python\n# Author: Bas Swinckels\n\nphi = np.arange(0, 10*np.pi, 0.1)\na = 1\nx = a*phi*np.cos(phi)\ny = a*phi*np.sin(phi)\n\ndr = (np.diff(x)**2 + np.diff(y)**2)**.5 # segment lengths\nr = np.zeros_like(x)\nr[1:] = np.cumsum(dr)                # integrate path\nr_int = np.linspace(0, r.max(), 200) # regular spaced path\nx_int = np.interp(r_int, r, x)       # integrate path\ny_int = np.interp(r_int, r, y)\n```\n#### 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. (★★★)\n`hint: np.logical_and.reduce, np.mod`\n\n```python\n# Author: Evgeni Burovski\n\nX = 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]])\nn = 4\nM = np.logical_and.reduce(np.mod(X, 1) == 0, axis=-1)\nM &= (X.sum(axis=-1) == n)\nprint(X[M])\n```\n#### 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). (★★★)\n`hint: np.percentile`\n\n```python\n# Author: Jessica B. Hamrick\n\nX = np.random.randn(100) # random 1D array\nN = 1000 # number of bootstrap samples\nidx = np.random.randint(0, X.size, (N, X.size))\nmeans = X[idx].mean(axis=1)\nconfint = np.percentile(means, [2.5, 97.5])\nprint(confint)\n```"
  },
  {
    "path": "100_Numpy_exercises_with_solutions.md",
    "content": "\n\n\n# 100 numpy exercises\n\nThis is a collection of exercises that have been collected in the numpy mailing list, on stack overflow\nand in the numpy documentation. The goal of this collection is to offer a quick reference for both old\nand new users but also to provide a set of exercises for those who teach.\n\n\nIf you find an error or think you've a better way to solve some of them, feel\nfree to open an issue at <https://github.com/rougier/numpy-100>.\nFile automatically generated. See the documentation to update questions/answers/hints programmatically.\n\n#### 1. Import the numpy package under the name `np` (★☆☆)\n\n\n```python\nimport numpy as np\n```\n#### 2. Print the numpy version and the configuration (★☆☆)\n\n\n```python\nprint(np.__version__)\nnp.show_config()\n```\n#### 3. Create a null vector of size 10 (★☆☆)\n\n\n```python\nZ = np.zeros(10)\nprint(Z)\n```\n#### 4. How to find the memory size of any array (★☆☆)\n\n\n```python\nZ = np.zeros((10,10))\nprint(\"%d bytes\" % (Z.size * Z.itemsize))\n\n# Simpler alternative\nprint(\"%d bytes\" % Z.nbytes)\n```\n#### 5. How to get the documentation of the numpy add function from the command line? (★☆☆)\n\n\n```python\n%run `python -c \"import numpy; numpy.info(numpy.add)\"`\n```\n#### 6. Create a null vector of size 10 but the fifth value which is 1 (★☆☆)\n\n\n```python\nZ = np.zeros(10)\nZ[4] = 1\nprint(Z)\n```\n#### 7. Create a vector with values ranging from 10 to 49 (★☆☆)\n\n\n```python\nZ = np.arange(10,50)\nprint(Z)\n```\n#### 8. Reverse a vector (first element becomes last) (★☆☆)\n\n\n```python\nZ = np.arange(50)\nZ = Z[::-1]\nprint(Z)\n```\n#### 9. Create a 3x3 matrix with values ranging from 0 to 8 (★☆☆)\n\n\n```python\nZ = np.arange(9).reshape(3, 3)\nprint(Z)\n```\n#### 10. Find indices of non-zero elements from [1,2,0,0,4,0] (★☆☆)\n\n\n```python\nnz = np.nonzero([1,2,0,0,4,0])\nprint(nz)\n```\n#### 11. Create a 3x3 identity matrix (★☆☆)\n\n\n```python\nZ = np.eye(3)\nprint(Z)\n```\n#### 12. Create a 3x3x3 array with random values (★☆☆)\n\n\n```python\nZ = np.random.random((3,3,3))\nprint(Z)\n```\n#### 13. Create a 10x10 array with random values and find the minimum and maximum values (★☆☆)\n\n\n```python\nZ = np.random.random((10,10))\nZmin, Zmax = Z.min(), Z.max()\nprint(Zmin, Zmax)\n```\n#### 14. Create a random vector of size 30 and find the mean value (★☆☆)\n\n\n```python\nZ = np.random.random(30)\nm = Z.mean()\nprint(m)\n```\n#### 15. Create a 2d array with 1 on the border and 0 inside (★☆☆)\n\n\n```python\nZ = np.ones((10,10))\nZ[1:-1,1:-1] = 0\nprint(Z)\n```\n#### 16. How to add a border (filled with 0's) around an existing array? (★☆☆)\n\n\n```python\nZ = np.ones((5,5))\nZ = np.pad(Z, pad_width=1, mode='constant', constant_values=0)\nprint(Z)\n\n# Not a solution to this problem but good to know: using fancy indexing for in-place edit\nZ[:, [0, -1]] = 0\nZ[[0, -1], :] = 0\nprint(Z)\n```\n#### 17. What is the result of the following expression? (★☆☆)\n```python\n0 * np.nan\nnp.nan == np.nan\nnp.inf > np.nan\nnp.nan - np.nan\nnp.nan in set([np.nan])\n0.3 == 3 * 0.1\n```\n\n\n```python\nprint(0 * np.nan)\nprint(np.nan == np.nan)\nprint(np.inf > np.nan)\nprint(np.nan - np.nan)\nprint(np.nan in set([np.nan]))\nprint(0.3 == 3 * 0.1)\n```\n#### 18. Create a 5x5 matrix with values 1,2,3,4 just below the diagonal (★☆☆)\n\n\n```python\nZ = np.diag(1+np.arange(4),k=-1)\nprint(Z)\n```\n#### 19. Create a 8x8 matrix and fill it with a checkerboard pattern (★☆☆)\n\n\n```python\nZ = np.zeros((8,8),dtype=int)\nZ[1::2,::2] = 1\nZ[::2,1::2] = 1\nprint(Z)\n```\n#### 20. Consider a (6,7,8) shape array, what is the index (x,y,z) of the 100th element? (★☆☆)\n\n\n```python\nprint(np.unravel_index(99,(6,7,8)))\n```\n#### 21. Create a checkerboard 8x8 matrix using the tile function (★☆☆)\n\n\n```python\nZ = np.tile( np.array([[0,1],[1,0]]), (4,4))\nprint(Z)\n```\n#### 22. Normalize a 5x5 random matrix (★☆☆)\n\n\n```python\nZ = np.random.random((5,5))\nZ = (Z - np.mean (Z)) / (np.std (Z))\nprint(Z)\n```\n#### 23. Create a custom dtype that describes a color as four unsigned bytes (RGBA) (★☆☆)\n\n\n```python\ncolor = np.dtype([(\"r\", np.ubyte),\n                  (\"g\", np.ubyte),\n                  (\"b\", np.ubyte),\n                  (\"a\", np.ubyte)])\n```\n#### 24. Multiply a 5x3 matrix by a 3x2 matrix (real matrix product) (★☆☆)\n\n\n```python\nZ = np.matmul(np.ones((5, 3)), np.ones((3, 2)))\nprint(Z)\n\n# Alternative solution, in Python 3.5 and above\nZ = np.ones((5,3)) @ np.ones((3,2))\nprint(Z)\n```\n#### 25. Given a 1D array, negate all elements which are between 3 and 8, in place. (★☆☆)\n\n\n```python\n# Author: Evgeni Burovski\n\nZ = np.arange(11)\nZ[(3 < Z) & (Z < 8)] *= -1\nprint(Z)\n```\n#### 26. What is the output of the following script? (★☆☆)\n```python\n# Author: Jake VanderPlas\n\nprint(sum(range(5),-1))\nfrom numpy import *\nprint(sum(range(5),-1))\n```\n\n\n```python\n# Author: Jake VanderPlas\n\nprint(sum(range(5),-1))\nfrom numpy import *\nprint(sum(range(5),-1))\n```\n#### 27. Consider an integer vector Z, which of these expressions are legal? (★☆☆)\n```python\nZ**Z\n2 << Z >> 2\nZ <- Z\n1j*Z\nZ/1/1\nZ<Z>Z\n```\n\n\n```python\nZ**Z\n2 << Z >> 2\nZ <- Z\n1j*Z\nZ/1/1\nZ<Z>Z\n```\n#### 28. What are the result of the following expressions? (★☆☆)\n```python\nnp.array(0) / np.array(0)\nnp.array(0) // np.array(0)\nnp.array([np.nan]).astype(int).astype(float)\n```\n\n\n```python\nprint(np.array(0) / np.array(0))\nprint(np.array(0) // np.array(0))\nprint(np.array([np.nan]).astype(int).astype(float))\n```\n#### 29. How to round away from zero a float array ? (★☆☆)\n\n\n```python\n# Author: Charles R Harris\n\nZ = np.random.uniform(-10,+10,10)\nprint(np.copysign(np.ceil(np.abs(Z)), Z))\n\n# More readable but less efficient\nprint(np.where(Z>0, np.ceil(Z), np.floor(Z)))\n```\n#### 30. How to find common values between two arrays? (★☆☆)\n\n\n```python\nZ1 = np.random.randint(0,10,10)\nZ2 = np.random.randint(0,10,10)\nprint(np.intersect1d(Z1,Z2))\n```\n#### 31. How to ignore all numpy warnings (not recommended)? (★☆☆)\n\n\n```python\n# Suicide mode on\ndefaults = np.seterr(all=\"ignore\")\nZ = np.ones(1) / 0\n\n# Back to sanity\n_ = np.seterr(**defaults)\n\n# Equivalently with a context manager\nwith np.errstate(all=\"ignore\"):\n    np.arange(3) / 0\n```\n#### 32. Is the following expressions true? (★☆☆)\n```python\nnp.sqrt(-1) == np.emath.sqrt(-1)\n```\n\n\n```python\nnp.sqrt(-1) == np.emath.sqrt(-1)\n```\n#### 33. How to get the dates of yesterday, today and tomorrow? (★☆☆)\n\n\n```python\nyesterday = np.datetime64('today') - np.timedelta64(1)\ntoday     = np.datetime64('today')\ntomorrow  = np.datetime64('today') + np.timedelta64(1)\n```\n#### 34. How to get all the dates corresponding to the month of July 2016? (★★☆)\n\n\n```python\nZ = np.arange('2016-07', '2016-08', dtype='datetime64[D]')\nprint(Z)\n```\n#### 35. How to compute ((A+B)*(-A/2)) in place (without copy)? (★★☆)\n\n\n```python\nA = np.ones(3)*1\nB = np.ones(3)*2\nnp.add(A,B,out=B)\nnp.divide(A,2,out=A)\nnp.negative(A,out=A)\nnp.multiply(A,B,out=A)\n```\n#### 36. Extract the integer part of a random array of positive numbers using 4 different methods (★★☆)\n\n\n```python\nZ = np.random.uniform(0,10,10)\n\nprint(Z - Z%1)\nprint(Z // 1)\nprint(np.floor(Z))\nprint(Z.astype(int))\nprint(np.trunc(Z))\n```\n#### 37. Create a 5x5 matrix with row values ranging from 0 to 4 (★★☆)\n\n\n```python\nZ = np.zeros((5,5))\nZ += np.arange(5)\nprint(Z)\n\n# without broadcasting\nZ = np.tile(np.arange(0, 5), (5,1))\nprint(Z)\n```\n#### 38. Consider a generator function that generates 10 integers and use it to build an array (★☆☆)\n\n\n```python\ndef generate():\n    for x in range(10):\n        yield x\nZ = np.fromiter(generate(),dtype=float,count=-1)\nprint(Z)\n```\n#### 39. Create a vector of size 10 with values ranging from 0 to 1, both excluded (★★☆)\n\n\n```python\nZ = np.linspace(0,1,11,endpoint=False)[1:]\nprint(Z)\n```\n#### 40. Create a random vector of size 10 and sort it (★★☆)\n\n\n```python\nZ = np.random.random(10)\nZ.sort()\nprint(Z)\n```\n#### 41. How to sum a small array faster than np.sum? (★★☆)\n\n\n```python\n# Author: Evgeni Burovski\n\nZ = np.arange(10)\nnp.add.reduce(Z)\n```\n#### 42. Consider two random arrays A and B, check if they are equal (★★☆)\n\n\n```python\nA = np.random.randint(0,2,5)\nB = np.random.randint(0,2,5)\n\n# Assuming identical shape of the arrays and a tolerance for the comparison of values\nequal = np.allclose(A,B)\nprint(equal)\n\n# Checking both the shape and the element values, no tolerance (values have to be exactly equal)\nequal = np.array_equal(A,B)\nprint(equal)\n```\n#### 43. Make an array immutable (read-only) (★★☆)\n\n\n```python\nZ = np.zeros(10)\nZ.flags.writeable = False\nZ[0] = 1\n```\n#### 44. Consider a random 10x2 matrix representing cartesian coordinates, convert them to polar coordinates (★★☆)\n\n\n```python\nZ = np.random.random((10,2))\nX,Y = Z[:,0], Z[:,1]\nR = np.sqrt(X**2+Y**2)\nT = np.arctan2(Y,X)\nprint(R)\nprint(T)\n```\n#### 45. Create random vector of size 10 and replace the maximum value by 0 (★★☆)\n\n\n```python\nZ = np.random.random(10)\nZ[Z.argmax()] = 0\nprint(Z)\n```\n#### 46. Create a structured array with `x` and `y` coordinates covering the [0,1]x[0,1] area (★★☆)\n\n\n```python\nZ = np.zeros((5,5), [('x',float),('y',float)])\nZ['x'], Z['y'] = np.meshgrid(np.linspace(0,1,5),\n                             np.linspace(0,1,5))\nprint(Z)\n```\n#### 47. Given two arrays, X and Y, construct the Cauchy matrix C (Cij =1/(xi - yj)) (★★☆)\n\n\n```python\n# Author: Evgeni Burovski\n\nX = np.arange(8)\nY = X + 0.5\nC = 1.0 / np.subtract.outer(X, Y)\nprint(np.linalg.det(C))\n```\n#### 48. Print the minimum and maximum representable values for each numpy scalar type (★★☆)\n\n\n```python\nfor dtype in [np.int8, np.int32, np.int64]:\n   print(np.iinfo(dtype).min)\n   print(np.iinfo(dtype).max)\nfor dtype in [np.float32, np.float64]:\n   print(np.finfo(dtype).min)\n   print(np.finfo(dtype).max)\n   print(np.finfo(dtype).eps)\n```\n#### 49. How to print all the values of an array? (★★☆)\n\n\n```python\nnp.set_printoptions(threshold=float(\"inf\"))\nZ = np.zeros((40,40))\nprint(Z)\n```\n#### 50. How to find the closest value (to a given scalar) in a vector? (★★☆)\n\n\n```python\nZ = np.arange(100)\nv = np.random.uniform(0,100)\nindex = (np.abs(Z-v)).argmin()\nprint(Z[index])\n```\n#### 51. Create a structured array representing a position (x,y) and a color (r,g,b) (★★☆)\n\n\n```python\nZ = np.zeros(10, [ ('position', [ ('x', float, 1),\n                                  ('y', float, 1)]),\n                   ('color',    [ ('r', float, 1),\n                                  ('g', float, 1),\n                                  ('b', float, 1)])])\nprint(Z)\n```\n#### 52. Consider a random vector with shape (100,2) representing coordinates, find point by point distances (★★☆)\n\n\n```python\nZ = np.random.random((10,2))\nX,Y = np.atleast_2d(Z[:,0], Z[:,1])\nD = np.sqrt( (X-X.T)**2 + (Y-Y.T)**2)\nprint(D)\n\n# Much faster with scipy\nimport scipy\n# Thanks Gavin Heverly-Coulson (#issue 1)\nimport scipy.spatial\n\nZ = np.random.random((10,2))\nD = scipy.spatial.distance.cdist(Z,Z)\nprint(D)\n```\n#### 53. How to convert a float (32 bits) array into an integer (32 bits) array in place?\n\n\n```python\n# Thanks Vikas (https://stackoverflow.com/a/10622758/5989906)\n# & unutbu (https://stackoverflow.com/a/4396247/5989906)\nZ = (np.random.rand(10)*100).astype(np.float32)\nY = Z.view(np.int32)\nY[:] = Z\nprint(Y)\n```\n#### 54. How to read the following file? (★★☆)\n```\n1, 2, 3, 4, 5\n6,  ,  , 7, 8\n ,  , 9,10,11\n```\n\n\n```python\nfrom io import StringIO\n\n# Fake file\ns = StringIO('''1, 2, 3, 4, 5\n\n                6,  ,  , 7, 8\n\n                 ,  , 9,10,11\n''')\nZ = np.genfromtxt(s, delimiter=\",\", dtype = int, filling_values = 0)\nprint(Z)\n```\n#### 55. What is the equivalent of enumerate for numpy arrays? (★★☆)\n\n\n```python\nZ = np.arange(9).reshape(3,3)\nfor index, value in np.ndenumerate(Z):\n    print(index, value)\nfor index in np.ndindex(Z.shape):\n    print(index, Z[index])\n```\n#### 56. Generate a generic 2D Gaussian-like array (★★☆)\n\n\n```python\nX, Y = np.meshgrid(np.linspace(-1,1,10), np.linspace(-1,1,10))\nD = np.sqrt(X*X+Y*Y)\nsigma, mu = 1.0, 0.0\nG = np.exp(-( (D-mu)**2 / ( 2.0 * sigma**2 ) ) )\nprint(G)\n```\n#### 57. How to randomly place p elements in a 2D array? (★★☆)\n\n\n```python\n# Author: Divakar\n\nn = 10\np = 3\nZ = np.zeros((n,n))\nnp.put(Z, np.random.choice(range(n*n), p, replace=False),1)\nprint(Z)\n```\n#### 58. Subtract the mean of each row of a matrix (★★☆)\n\n\n```python\n# Author: Warren Weckesser\n\nX = np.random.rand(5, 10)\n\n# Recent versions of numpy\nY = X - X.mean(axis=1, keepdims=True)\n\n# Older versions of numpy\nY = X - X.mean(axis=1).reshape(-1, 1)\n\nprint(Y)\n```\n#### 59. How to sort an array by the nth column? (★★☆)\n\n\n```python\n# Author: Steve Tjoa\n\nZ = np.random.randint(0,10,(3,3))\nprint(Z)\nprint(Z[Z[:,1].argsort()])\n```\n#### 60. How to tell if a given 2D array has null columns? (★★☆)\n\n\n```python\n# Author: Warren Weckesser\n\n# null : 0 \nZ = np.random.randint(0,3,(3,10))\nprint((~Z.any(axis=0)).any())\n\n# null : np.nan\nZ=np.array([\n    [0,1,np.nan],\n    [1,2,np.nan],\n    [4,5,np.nan]\n])\nprint(np.isnan(Z).all(axis=0))\n```\n#### 61. Find the nearest value from a given value in an array (★★☆)\n\n\n```python\nZ = np.random.uniform(0,1,10)\nz = 0.5\nm = Z.flat[np.abs(Z - z).argmin()]\nprint(m)\n```\n#### 62. Considering two arrays with shape (1,3) and (3,1), how to compute their sum using an iterator? (★★☆)\n\n\n```python\nA = np.arange(3).reshape(3,1)\nB = np.arange(3).reshape(1,3)\nit = np.nditer([A,B,None])\nfor x,y,z in it: z[...] = x + y\nprint(it.operands[2])\n```\n#### 63. Create an array class that has a name attribute (★★☆)\n\n\n```python\nclass 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.name = getattr(obj, 'name', \"no name\")\n\nZ = NamedArray(np.arange(10), \"range_10\")\nprint (Z.name)\n```\n#### 64. Consider a given vector, how to add 1 to each element indexed by a second vector (be careful with repeated indices)? (★★★)\n\n\n```python\n# Author: Brett Olsen\n\nZ = np.ones(10)\nI = np.random.randint(0,len(Z),20)\nZ += np.bincount(I, minlength=len(Z))\nprint(Z)\n\n# Another solution\n# Author: Bartosz Telenczuk\nnp.add.at(Z, I, 1)\nprint(Z)\n```\n#### 65. How to accumulate elements of a vector (X) to an array (F) based on an index list (I)? (★★★)\n\n\n```python\n# Author: Alan G Isaac\n\nX = [1,2,3,4,5,6]\nI = [1,3,9,3,4,1]\nF = np.bincount(I,X)\nprint(F)\n```\n#### 66. Considering a (w,h,3) image of (dtype=ubyte), compute the number of unique colors (★★☆)\n\n\n```python\n# Author: Fisher Wang\n\nw, h = 256, 256\nI = np.random.randint(0, 4, (h, w, 3)).astype(np.ubyte)\ncolors = np.unique(I.reshape(-1, 3), axis=0)\nn = len(colors)\nprint(n)\n\n# Faster version\n# Author: Mark Setchell\n# https://stackoverflow.com/a/59671950/2836621\n\nw, h = 256, 256\nI = np.random.randint(0,4,(h,w,3), dtype=np.uint8)\n\n# View each pixel as a single 24-bit integer, rather than three 8-bit bytes\nI24 = np.dot(I.astype(np.uint32),[1,256,65536])\n\n# Count unique colours\nn = len(np.unique(I24))\nprint(n)\n```\n#### 67. Considering a four dimensions array, how to get sum over the last two axis at once? (★★★)\n\n\n```python\nA = np.random.randint(0,10,(3,4,3,4))\n# solution by passing a tuple of axes (introduced in numpy 1.7.0)\nsum = A.sum(axis=(-2,-1))\nprint(sum)\n# solution by flattening the last two dimensions into one\n# (useful for functions that don't accept tuples for axis argument)\nsum = A.reshape(A.shape[:-2] + (-1,)).sum(axis=-1)\nprint(sum)\n```\n#### 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? (★★★)\n\n\n```python\n# Author: Jaime Fernández del Río\n\nD = np.random.uniform(0,1,100)\nS = np.random.randint(0,10,100)\nD_sums = np.bincount(S, weights=D)\nD_counts = np.bincount(S)\nD_means = D_sums / D_counts\nprint(D_means)\n\n# Pandas solution as a reference due to more intuitive code\nimport pandas as pd\nprint(pd.Series(D).groupby(S).mean())\n```\n#### 69. How to get the diagonal of a dot product? (★★★)\n\n\n```python\n# Author: Mathieu Blondel\n\nA = np.random.uniform(0,1,(5,5))\nB = np.random.uniform(0,1,(5,5))\n\n# Slow version\nnp.diag(np.dot(A, B))\n\n# Fast version\nnp.sum(A * B.T, axis=1)\n\n# Faster version\nnp.einsum(\"ij,ji->i\", A, B)\n```\n#### 70. Consider the vector [1, 2, 3, 4, 5], how to build a new vector with 3 consecutive zeros interleaved between each value? (★★★)\n\n\n```python\n# Author: Warren Weckesser\n\nZ = np.array([1,2,3,4,5])\nnz = 3\nZ0 = np.zeros(len(Z) + (len(Z)-1)*(nz))\nZ0[::nz+1] = Z\nprint(Z0)\n```\n#### 71. Consider an array of dimension (5,5,3), how to multiply it by an array with dimensions (5,5)? (★★★)\n\n\n```python\nA = np.ones((5,5,3))\nB = 2*np.ones((5,5))\nprint(A * B[:,:,None])\n```\n#### 72. How to swap two rows of an array? (★★★)\n\n\n```python\n# Author: Eelco Hoogendoorn\n\nA = np.arange(25).reshape(5,5)\nA[[0,1]] = A[[1,0]]\nprint(A)\n```\n#### 73. Consider a set of 10 triplets describing 10 triangles (with shared vertices), find the set of unique line segments composing all the  triangles (★★★)\n\n\n```python\n# Author: Nicolas P. Rougier\n\nfaces = np.random.randint(0,100,(10,3))\nF = np.roll(faces.repeat(2,axis=1),-1,axis=1)\nF = F.reshape(len(F)*3,2)\nF = np.sort(F,axis=1)\nG = F.view( dtype=[('p0',F.dtype),('p1',F.dtype)] )\nG = np.unique(G)\nprint(G)\n```\n#### 74. Given a sorted array C that corresponds to a bincount, how to produce an array A such that np.bincount(A) == C? (★★★)\n\n\n```python\n# Author: Jaime Fernández del Río\n\nC = np.bincount([1,1,2,3,4,4,6])\nA = np.repeat(np.arange(len(C)), C)\nprint(A)\n```\n#### 75. How to compute averages using a sliding window over an array? (★★★)\n\n\n```python\n# Author: Jaime Fernández del Río\n\ndef 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\nZ = np.arange(20)\nprint(moving_average(Z, n=3))\n\n# Author: Jeff Luo (@Jeff1999)\n# make sure your NumPy >= 1.20.0\n\nfrom numpy.lib.stride_tricks import sliding_window_view\n\nZ = np.arange(20)\nprint(sliding_window_view(Z, window_shape=3).mean(axis=-1))\n```\n#### 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]) (★★★)\n\n\n```python\n# Author: Joe Kington / Erik Rigtorp\nfrom numpy.lib import stride_tricks\n\ndef rolling(a, window):\n    shape = (a.size - window + 1, window)\n    strides = (a.strides[0], a.strides[0])\n    return stride_tricks.as_strided(a, shape=shape, strides=strides)\nZ = rolling(np.arange(10), 3)\nprint(Z)\n\n# Author: Jeff Luo (@Jeff1999)\n\nZ = np.arange(10)\nprint(sliding_window_view(Z, window_shape=3))\n```\n#### 77. How to negate a boolean, or to change the sign of a float inplace? (★★★)\n\n\n```python\n# Author: Nathaniel J. Smith\n\nZ = np.random.randint(0,2,100)\nnp.logical_not(Z, out=Z)\n\nZ = np.random.uniform(-1.0,1.0,100)\nnp.negative(Z, out=Z)\n```\n#### 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])? (★★★)\n\n\n```python\nP0 = np.random.uniform(-10,10,(10,2))\nP1 = np.random.uniform(-10,10,(10,2))\np  = np.random.uniform(-10,10,( 1,2))\n\ndef distance_faster(P0,P1,p):\n    #Author: Hemanth Pasupuleti\n    #Reference: https://mathworld.wolfram.com/Point-LineDistance2-Dimensional.html\n\n    v = P1- P0 \n    v[:,[0,1]] = v[:,[1,0]]\n    v[:,1]*=-1 \n    norm = np.linalg.norm(v,axis=1)   \n    r = P0 - p\n    d = np.abs(np.einsum(\"ij,ij->i\",r,v)) / norm \n\n    return d\n\nprint(distance_faster(P0, P1, p))\n\n##--------------- OR ---------------##\ndef distance_slower(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\nprint(distance_slower(P0, P1, p))\n```\n#### 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])? (★★★)\n\n\n```python\n# Author: Italmassov Kuanysh\n\n# based on distance function from previous question\nP0 = np.random.uniform(-10, 10, (10,2))\nP1 = np.random.uniform(-10,10,(10,2))\np = np.random.uniform(-10, 10, (10,2))\nprint(np.array([distance(P0,P1,p_i) for p_i in p]))\n\n# Author: Yang Wu (Broadcasting)\ndef distance_points_to_lines(p: np.ndarray, p_1: np.ndarray, p_2: np.ndarray) -> np.ndarray:\n    x_0, y_0 = p.T  # Shape -> (n points, )\n    x_1, y_1 = p_1.T  # Shape -> (n lines, )\n    x_2, y_2 = p_2.T  # Shape -> (n lines, )\n\n    # Displacement vector coordinates from p_1 -> p_2\n    dx = x_2 - x_1  # Shape -> (n lines, )\n    dy = y_2 - y_1  # Shape -> (n lines, )\n\n    # The 'cross product' term\n    cross_term = x_2 * y_1 - y_2 * x_1  # Shape -> (n lines, )\n\n    # Broadcast x_0, y_0 (n points, 1) and dx, dy, cross_term (1, n lines) -> (n points, n lines)\n    numerator = np.abs(\n        dy[np.newaxis, :] * x_0[:, np.newaxis]\n        - dx[np.newaxis, :] * y_0[:, np.newaxis]\n        + cross_term[np.newaxis, :]\n    )\n    denominator = np.sqrt(dx**2 + dy**2)  # Shape -> (n lines, )\n\n    # Shape (n points, n lines) / (1, n_lines) -> (n points, n lines)\n    return numerator / denominator[np.newaxis, :]\n\ndistance_points_to_lines(p, P0, P1)\n```\n#### 80. Consider an arbitrary array, write a function that extracts a subpart with a fixed shape and centered on a given element (pad with a `fill` value when necessary) (★★★)\n\n\n```python\n# Author: Nicolas Rougier\n\nZ = np.random.randint(0,10,(10,10))\nshape = (5,5)\nfill  = 0\nposition = (1,1)\n\nR = np.ones(shape, dtype=Z.dtype)*fill\nP  = np.array(list(position)).astype(int)\nRs = np.array(list(R.shape)).astype(int)\nZs = np.array(list(Z.shape)).astype(int)\n\nR_start = np.zeros((len(shape),)).astype(int)\nR_stop  = np.array(list(shape)).astype(int)\nZ_start = (P-Rs//2)\nZ_stop  = (P+Rs//2)+Rs%2\n\nR_start = (R_start - np.minimum(Z_start,0)).tolist()\nZ_start = (np.maximum(Z_start,0)).tolist()\nR_stop = np.maximum(R_start, (R_stop - np.maximum(Z_stop-Zs,0))).tolist()\nZ_stop = (np.minimum(Z_stop,Zs)).tolist()\n\nr = tuple([slice(start,stop) for start,stop in zip(R_start,R_stop)])\nz = tuple([slice(start,stop) for start,stop in zip(Z_start,Z_stop)])\nR[r] = Z[z]\nprint(Z)\nprint(R)\n```\n#### 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]]? (★★★)\n\n\n```python\n# Author: Stefan van der Walt\n\nZ = np.arange(1,15,dtype=np.uint32)\nR = stride_tricks.as_strided(Z,(11,4),(4,4))\nprint(R)\n\n# Author: Jeff Luo (@Jeff1999)\n\nZ = np.arange(1, 15, dtype=np.uint32)\nprint(sliding_window_view(Z, window_shape=4))\n```\n#### 82. Compute a matrix rank (★★★)\n\n\n```python\n# Author: Stefan van der Walt\n\nZ = np.random.uniform(0,1,(10,10))\nU, S, V = np.linalg.svd(Z) # Singular Value Decomposition\nthreshold = len(S) * S.max() * np.finfo(S.dtype).eps\nrank = np.sum(S > threshold)\nprint(rank)\n\n# alternative solution:\n# Author: Jeff Luo (@Jeff1999)\n\nrank = np.linalg.matrix_rank(Z)\nprint(rank)\n```\n#### 83. How to find the most frequent value in an array?\n\n\n```python\nZ = np.random.randint(0,10,50)\nprint(np.bincount(Z).argmax())\n```\n#### 84. Extract all the contiguous 3x3 blocks from a random 10x10 matrix (★★★)\n\n\n```python\n# Author: Chris Barker\n\nZ = np.random.randint(0,5,(10,10))\nn = 3\ni = 1 + (Z.shape[0]-3)\nj = 1 + (Z.shape[1]-3)\nC = stride_tricks.as_strided(Z, shape=(i, j, n, n), strides=Z.strides + Z.strides)\nprint(C)\n\n# Author: Jeff Luo (@Jeff1999)\n\nZ = np.random.randint(0,5,(10,10))\nprint(sliding_window_view(Z, window_shape=(3, 3)))\n```\n#### 85. Create a 2D array subclass such that Z[i,j] == Z[j,i] (★★★)\n\n\n```python\n# Author: Eric O. Lebigot\n# Note: only works for 2d array and value setting using indices\n\nclass 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\ndef symetric(Z):\n    return np.asarray(Z + Z.T - np.diag(Z.diagonal())).view(Symetric)\n\nS = symetric(np.random.randint(0,10,(5,5)))\nS[2,3] = 42\nprint(S)\n```\n#### 86. Consider a set of p matrices with 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)) (★★★)\n\n\n```python\n# Author: Stefan van der Walt\n\np, n = 10, 20\nM = np.ones((p,n,n))\nV = np.ones((p,n,1))\nS = np.tensordot(M, V, axes=[[0, 2], [0, 1]])\nprint(S)\n\n# It works, because:\n# M is (p,n,n)\n# V is (p,n,1)\n# Thus, summing over the paired axes 0 and 0 (of M and V independently),\n# and 2 and 1, to remain with a (n,1) vector.\n```\n#### 87. Consider a 16x16 array, how to get the block-sum (block size is 4x4)? (★★★)\n\n\n```python\n# Author: Robert Kern\n\nZ = np.ones((16,16))\nk = 4\nS = 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)\nprint(S)\n\n# alternative solution:\n# Author: Sebastian Wallkötter (@FirefoxMetzger)\n\nZ = np.ones((16,16))\nk = 4\n\nwindows = np.lib.stride_tricks.sliding_window_view(Z, (k, k))\nS = windows[::k, ::k, ...].sum(axis=(-2, -1))\n\n# alternative solution (by @Gattocrucco)\nS = Z.reshape(4, 4, 4, 4).sum((1, 3))\n```\n#### 88. How to implement the Game of Life using numpy arrays? (★★★)\n\n\n```python\n# Author: Nicolas Rougier\n\ndef 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\nZ = np.random.randint(0,2,(50,50))\nfor i in range(100): Z = iterate(Z)\nprint(Z)\n```\n#### 89. How to get the n largest values of an array (★★★)\n\n\n```python\nZ = np.arange(10000)\nnp.random.shuffle(Z)\nn = 5\n\n# Slow\nprint (Z[np.argsort(Z)[-n:]])\n\n# Fast\nprint (Z[np.argpartition(-Z,n)[:n]])\n```\n#### 90. Given an arbitrary number of vectors, build the cartesian product (every combination of every item) (★★★)\n\n\n```python\n# Author: Stefan Van der Walt\n\ndef 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\nprint (cartesian(([1, 2, 3], [4, 5], [6, 7])))\n```\n#### 91. How to create a record array from a regular array? (★★★)\n\n\n```python\nZ = np.array([(\"Hello\", 2.5, 3),\n              (\"World\", 3.6, 2)])\nR = np.core.records.fromarrays(Z.T,\n                               names='col1, col2, col3',\n                               formats = 'S8, f8, i8')\nprint(R)\n```\n#### 92. Consider a large vector Z, compute Z to the power of 3 using 3 different methods (★★★)\n\n\n```python\n# Author: Ryan G.\n\nx = np.random.rand(int(5e7))\n\n%timeit np.power(x,3)\n%timeit x*x*x\n%timeit np.einsum('i,i,i->i',x,x,x)\n```\n#### 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? (★★★)\n\n\n```python\n# Author: Gabe Schwartz\n\nA = np.random.randint(0,5,(8,3))\nB = np.random.randint(0,5,(2,2))\n\nC = (A[..., np.newaxis, np.newaxis] == B)\nrows = np.where(C.any((3,1)).all(1))[0]\nprint(rows)\n```\n#### 94. Considering a 10x3 matrix, extract rows with unequal values (e.g. [2,2,3]) (★★★)\n\n\n```python\n# Author: Robert Kern\n\nZ = np.random.randint(0,5,(10,3))\nprint(Z)\n# solution for arrays of all dtypes (including string arrays and record arrays)\nE = np.all(Z[:,1:] == Z[:,:-1], axis=1)\nU = Z[~E]\nprint(U)\n# soluiton for numerical arrays only, will work for any number of columns in Z\nU = Z[Z.max(axis=1) != Z.min(axis=1),:]\nprint(U)\n```\n#### 95. Convert a vector of ints into a matrix binary representation (★★★)\n\n\n```python\n# Author: Warren Weckesser\n\nI = np.array([0, 1, 2, 3, 15, 16, 32, 64, 128])\nB = ((I.reshape(-1,1) & (2**np.arange(8))) != 0).astype(int)\nprint(B[:,::-1])\n\n# Author: Daniel T. McDonald\n\nI = np.array([0, 1, 2, 3, 15, 16, 32, 64, 128], dtype=np.uint8)\nprint(np.unpackbits(I[:, np.newaxis], axis=1))\n```\n#### 96. Given a two dimensional array, how to extract unique rows? (★★★)\n\n\n```python\n# Author: Jaime Fernández del Río\n\nZ = np.random.randint(0,2,(6,3))\nT = np.ascontiguousarray(Z).view(np.dtype((np.void, Z.dtype.itemsize * Z.shape[1])))\n_, idx = np.unique(T, return_index=True)\nuZ = Z[idx]\nprint(uZ)\n\n# Author: Andreas Kouzelis\n# NumPy >= 1.13\nuZ = np.unique(Z, axis=0)\nprint(uZ)\n```\n#### 97. Considering 2 vectors A & B, write the einsum equivalent of inner, outer, sum, and mul function (★★★)\n\n\n```python\n# Author: Alex Riley\n# Make sure to read: http://ajcr.net/Basic-guide-to-einsum/\n\nA = np.random.uniform(0,1,10)\nB = np.random.uniform(0,1,10)\n\nnp.einsum('i->', A)       # np.sum(A)\nnp.einsum('i,i->i', A, B) # A * B\nnp.einsum('i,i', A, B)    # np.inner(A, B)\nnp.einsum('i,j->ij', A, B)    # np.outer(A, B)\n```\n#### 98. Considering a path described by two vectors (X,Y), how to sample it using equidistant samples (★★★)?\n\n\n```python\n# Author: Bas Swinckels\n\nphi = np.arange(0, 10*np.pi, 0.1)\na = 1\nx = a*phi*np.cos(phi)\ny = a*phi*np.sin(phi)\n\ndr = (np.diff(x)**2 + np.diff(y)**2)**.5 # segment lengths\nr = np.zeros_like(x)\nr[1:] = np.cumsum(dr)                # integrate path\nr_int = np.linspace(0, r.max(), 200) # regular spaced path\nx_int = np.interp(r_int, r, x)       # integrate path\ny_int = np.interp(r_int, r, y)\n```\n#### 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. (★★★)\n\n\n```python\n# Author: Evgeni Burovski\n\nX = 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]])\nn = 4\nM = np.logical_and.reduce(np.mod(X, 1) == 0, axis=-1)\nM &= (X.sum(axis=-1) == n)\nprint(X[M])\n```\n#### 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). (★★★)\n\n\n```python\n# Author: Jessica B. Hamrick\n\nX = np.random.randn(100) # random 1D array\nN = 1000 # number of bootstrap samples\nidx = np.random.randint(0, X.size, (N, X.size))\nmeans = X[idx].mean(axis=1)\nconfint = np.percentile(means, [2.5, 97.5])\nprint(confint)\n```"
  },
  {
    "path": "100_Numpy_random.ipynb",
    "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"a3747e86\",\n   \"metadata\": {},\n   \"source\": [\n    \"# 100 numpy exercises\\n\",\n    \"\\n\",\n    \"This is a collection of exercises that have been collected in the numpy mailing list, on stack overflow\\n\",\n    \"and in the numpy documentation. The goal of this collection is to offer a quick reference for both old\\n\",\n    \"and new users but also to provide a set of exercises for those who teach.\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"If you find an error or think you've a better way to solve some of them, feel\\n\",\n    \"free to open an issue at <https://github.com/rougier/numpy-100>.\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"8b9ef9a4\",\n   \"metadata\": {},\n   \"source\": [\n    \"File automatically generated. See the documentation to update questions/answers/hints programmatically.\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"id\": \"792c1217\",\n   \"metadata\": {},\n   \"source\": [\n    \"Run the `initialise.py` module, then call a random question with `pick()` an hint towards its solution with\\n\",\n    \"`hint(n)` and the answer with `answer(n)`, where n is the number of the picked question.\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"541f746c\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"%run initialise.py\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"d1743adb\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"pick()\"\n   ]\n  }\n ],\n \"metadata\": {},\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"
  },
  {
    "path": "LICENSE.txt",
    "content": "MIT License\n\nCopyright (c) 2016 Nicolas P. Rougier\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "## 100 numpy exercises\n\n[![Binder](http://mybinder.org/badge.svg)](http://mybinder.org:/repo/rougier/numpy-100/notebooks/100%20Numpy%20exercises.ipynb)\n\nThis is a collection of numpy exercises from numpy mailing list, stack overflow, and numpy documentation. I've also created some problems myself to reach the 100 limit. The goal of this collection is to offer a quick reference for both old and new users but also to provide a set of exercises for those who teach. For extended exercises, make sure to read [From Python to NumPy](http://www.labri.fr/perso/nrougier/from-python-to-numpy/).\n\n→ [Test them on Binder](http://mybinder.org:/repo/rougier/numpy-100/notebooks/100_Numpy_exercises.ipynb)  \n→ [Read them on GitHub](100_Numpy_exercises.md)  \n\nNote: markdown and ipython notebook are created programmatically from the source data in `source/exercises.ktx`.\nTo modify the content of these files, please change the text in the source and run the `generators.py` module with a python\ninterpreter with the libraries under `requirements.txt` installed.\n\nThe keyed text format (`ktx`) is a minimal human readable key-values to store text (markdown or others) indexed by keys. \n\nThis work is licensed under the MIT license.  \n[![DOI](https://zenodo.org/badge/10173/rougier/numpy-100.svg)](https://zenodo.org/badge/latestdoi/10173/rougier/numpy-100)\n\n\n### Variants in Other Languages\n\n - **Julia**: [100 Julia Exercises](https://github.com/RoyiAvital/Julia100Exercises).\n"
  },
  {
    "path": "generators.py",
    "content": "import os\nimport nbformat as nbf\nimport mdutils\n\n\ndef ktx_to_dict(input_file, keystarter='<'):\n    \"\"\" parsing keyed text to a python dictionary. \"\"\"\n    answer = dict()\n\n    with open(input_file, 'r+', encoding='utf-8') as f:\n        lines = f.readlines()\n\n    k, val = '', ''\n    for line in lines:\n        if line.startswith(keystarter):\n            k = line.replace(keystarter, '').strip()\n            val = ''\n        else:\n            val += line\n\n        if k:\n            answer.update({k: val.strip()})\n\n    return answer\n\n\ndef dict_to_ktx(input_dict, output_file, keystarter='<'):\n    \"\"\" Store a python dictionary to a keyed text\"\"\"\n    with open(output_file, 'w+') as f:\n        for k, val in input_dict.items():\n            f.write(f'{keystarter} {k}\\n')\n            f.write(f'{val}\\n\\n')\n\n\nHEADERS = ktx_to_dict(os.path.join('source', 'headers.ktx'))\nQHA = ktx_to_dict(os.path.join('source', 'exercises100.ktx'))\n\n\ndef create_jupyter_notebook(destination_filename='100_Numpy_exercises.ipynb'):\n    \"\"\" Programmatically create jupyter notebook with the questions (and hints and solutions if required)\n    saved under source files \"\"\"\n\n    # Create cells sequence\n    nb = nbf.v4.new_notebook()\n\n    nb['cells'] = []\n\n    # - Add header:\n    nb['cells'].append(nbf.v4.new_markdown_cell(HEADERS[\"header\"]))\n    nb['cells'].append(nbf.v4.new_markdown_cell(HEADERS[\"sub_header\"]))\n    nb['cells'].append(nbf.v4.new_markdown_cell(HEADERS[\"jupyter_instruction\"]))\n\n    # - Add initialisation\n    nb['cells'].append(nbf.v4.new_code_cell('%run initialise.py'))\n\n    # - Add questions and empty spaces for answers\n    for n in range(1, 101):\n        nb['cells'].append(nbf.v4.new_markdown_cell(f'#### {n}. ' + QHA[f'q{n}']))\n        nb['cells'].append(nbf.v4.new_code_cell(\"\"))\n\n    # Delete file if one with the same name is found\n    if os.path.exists(destination_filename):\n        os.remove(destination_filename)\n\n    # Write sequence to file\n    nbf.write(nb, destination_filename)\n\n\ndef create_jupyter_notebook_random_question(destination_filename='100_Numpy_random.ipynb'):\n    \"\"\" Programmatically create jupyter notebook with the questions (and hints and solutions if required)\n    saved under source files \"\"\"\n\n    # Create cells sequence\n    nb = nbf.v4.new_notebook()\n\n    nb['cells'] = []\n\n    # - Add header:\n    nb['cells'].append(nbf.v4.new_markdown_cell(HEADERS[\"header\"]))\n    nb['cells'].append(nbf.v4.new_markdown_cell(HEADERS[\"sub_header\"]))\n    nb['cells'].append(nbf.v4.new_markdown_cell(HEADERS[\"jupyter_instruction_rand\"]))\n\n    # - Add initialisation\n    nb['cells'].append(nbf.v4.new_code_cell('%run initialise.py'))\n    nb['cells'].append(nbf.v4.new_code_cell(\"pick()\"))\n\n    # Delete file if one with the same name is found\n    if os.path.exists(destination_filename):\n        os.remove(destination_filename)\n\n    # Write sequence to file\n    nbf.write(nb, destination_filename)\n\n\ndef create_markdown(destination_filename='100_Numpy_exercises', with_hints=False, with_solutions=False):\n    # Create file name\n    if with_hints:\n        destination_filename += '_with_hints'\n    if with_solutions:\n        destination_filename += '_with_solutions'\n\n    # Initialise file\n    mdfile = mdutils.MdUtils(file_name=destination_filename)\n\n    # Add headers\n    mdfile.write(HEADERS[\"header\"] + '\\n')\n    mdfile.write(HEADERS[\"sub_header\"] + '\\n')\n\n    # Add questions (and hint or answers if required)\n    for n in range(1, 101):\n        mdfile.new_header(title=f\"{n}. {QHA[f'q{n}']}\", level=4, add_table_of_contents=\"n\")\n        if with_hints:\n            mdfile.write(f\"`{QHA[f'h{n}']}`\")\n        if with_solutions:\n            mdfile.insert_code(QHA[f'a{n}'], language='python')\n\n    # Delete file if one with the same name is found\n    if os.path.exists(destination_filename):\n        os.remove(destination_filename)\n\n    # Write sequence to file\n    mdfile.create_md_file()\n\n\ndef create_rst(destination_filename, with_ints=False, with_answers=False):\n    # TODO: use rstdoc python library.\n    #  also see possible integrations with https://github.com/rougier/numpy-100/pull/38\n    pass\n\n\nif __name__ == '__main__':\n    create_jupyter_notebook()\n    create_jupyter_notebook_random_question()\n    create_markdown()\n    create_markdown(with_hints=False, with_solutions=True)\n    create_markdown(with_hints=True, with_solutions=False)\n    create_markdown(with_hints=True, with_solutions=True)\n"
  },
  {
    "path": "initialise.py",
    "content": "import numpy as np\n\nimport generators as ge\n\n\ndef question(n):\n    print(f'{n}. ' + ge.QHA[f'q{n}'])\n\n\ndef hint(n):\n    print(ge.QHA[f'h{n}'])\n\n\ndef answer(n):\n    print(ge.QHA[f'a{n}'])\n\n\ndef pick():\n    n = np.random.randint(1, 100)\n    question(n)\n"
  },
  {
    "path": "requirements.txt",
    "content": "numpy\nmdutils\nnbformat\n"
  },
  {
    "path": "runtime.txt",
    "content": "python-3.7.17\n"
  },
  {
    "path": "source/exercises100.ktx",
    "content": "< q1\nImport the numpy package under the name `np` (★☆☆)\n\n< h1\nhint: import … as\n\n< a1\nimport numpy as np\n\n< q2\nPrint the numpy version and the configuration (★☆☆)\n\n< h2\nhint: np.__version__, np.show_config)\n\n< a2\nprint(np.__version__)\nnp.show_config()\n\n< q3\nCreate a null vector of size 10 (★☆☆)\n\n< h3\nhint: np.zeros\n\n< a3\nZ = np.zeros(10)\nprint(Z)\n\n< q4\nHow to find the memory size of any array (★☆☆)\n\n< h4\nhint: size, itemsize\n\n< a4\nZ = np.zeros((10,10))\nprint(\"%d bytes\" % (Z.size * Z.itemsize))\n\n# Simpler alternative\nprint(\"%d bytes\" % Z.nbytes)\n\n< q5\nHow to get the documentation of the numpy add function from the command line? (★☆☆)\n\n< h5\nhint: np.info\n\n< a5\n%run `python -c \"import numpy; numpy.info(numpy.add)\"`\n\n< q6\nCreate a null vector of size 10 but the fifth value which is 1 (★☆☆)\n\n< h6\nhint: array[4]\n\n< a6\nZ = np.zeros(10)\nZ[4] = 1\nprint(Z)\n\n< q7\nCreate a vector with values ranging from 10 to 49 (★☆☆)\n\n< h7\nhint: arange\n\n< a7\nZ = np.arange(10,50)\nprint(Z)\n\n< q8\nReverse a vector (first element becomes last) (★☆☆)\n\n< h8\nhint: array[::-1]\n\n< a8\nZ = np.arange(50)\nZ = Z[::-1]\nprint(Z)\n\n< q9\nCreate a 3x3 matrix with values ranging from 0 to 8 (★☆☆)\n\n< h9\nhint: reshape\n\n< a9\nZ = np.arange(9).reshape(3, 3)\nprint(Z)\n\n< q10\nFind indices of non-zero elements from [1,2,0,0,4,0] (★☆☆)\n\n< h10\nhint: np.nonzero\n\n< a10\nnz = np.nonzero([1,2,0,0,4,0])\nprint(nz)\n\n< q11\nCreate a 3x3 identity matrix (★☆☆)\n\n< h11\nhint: np.eye\n\n< a11\nZ = np.eye(3)\nprint(Z)\n\n< q12\nCreate a 3x3x3 array with random values (★☆☆)\n\n< h12\nhint: np.random.random\n\n< a12\nZ = np.random.random((3,3,3))\nprint(Z)\n\n< q13\nCreate a 10x10 array with random values and find the minimum and maximum values (★☆☆)\n\n< h13\nhint: min, max\n\n< a13\nZ = np.random.random((10,10))\nZmin, Zmax = Z.min(), Z.max()\nprint(Zmin, Zmax)\n\n< q14\nCreate a random vector of size 30 and find the mean value (★☆☆)\n\n< h14\nhint: mean\n\n< a14\nZ = np.random.random(30)\nm = Z.mean()\nprint(m)\n\n< q15\nCreate a 2d array with 1 on the border and 0 inside (★☆☆)\n\n< h15\nhint: array[1:-1, 1:-1]\n\n< a15\nZ = np.ones((10,10))\nZ[1:-1,1:-1] = 0\nprint(Z)\n\n< q16\nHow to add a border (filled with 0's) around an existing array? (★☆☆)\n\n< h16\nhint: np.pad\n\n< a16\nZ = np.ones((5,5))\nZ = np.pad(Z, pad_width=1, mode='constant', constant_values=0)\nprint(Z)\n\n# Not a solution to this problem but good to know: using fancy indexing for in-place edit\nZ[:, [0, -1]] = 0\nZ[[0, -1], :] = 0\nprint(Z)\n\n< q17\nWhat is the result of the following expression? (★☆☆)\n```python\n0 * np.nan\nnp.nan == np.nan\nnp.inf > np.nan\nnp.nan - np.nan\nnp.nan in set([np.nan])\n0.3 == 3 * 0.1\n```\n\n< h17\nhint: NaN = not a number, inf = infinity\n\n< a17\nprint(0 * np.nan)\nprint(np.nan == np.nan)\nprint(np.inf > np.nan)\nprint(np.nan - np.nan)\nprint(np.nan in set([np.nan]))\nprint(0.3 == 3 * 0.1)\n\n< q18\nCreate a 5x5 matrix with values 1,2,3,4 just below the diagonal (★☆☆)\n\n< h18\nhint: np.diag\n\n< a18\nZ = np.diag(1+np.arange(4),k=-1)\nprint(Z)\n\n< q19\nCreate a 8x8 matrix and fill it with a checkerboard pattern (★☆☆)\n\n< h19\nhint: array[::2]\n\n< a19\nZ = np.zeros((8,8),dtype=int)\nZ[1::2,::2] = 1\nZ[::2,1::2] = 1\nprint(Z)\n\n< q20\nConsider a (6,7,8) shape array, what is the index (x,y,z) of the 100th element? (★☆☆)\n\n< h20\nhint: np.unravel_index\n\n< a20\nprint(np.unravel_index(99,(6,7,8)))\n\n< q21\nCreate a checkerboard 8x8 matrix using the tile function (★☆☆)\n\n< h21\nhint: np.tile\n\n< a21\nZ = np.tile( np.array([[0,1],[1,0]]), (4,4))\nprint(Z)\n\n< q22\nNormalize a 5x5 random matrix (★☆☆)\n\n< h22\nhint: (x -mean)/std\n\n< a22\nZ = np.random.random((5,5))\nZ = (Z - np.mean (Z)) / (np.std (Z))\nprint(Z)\n\n< q23\nCreate a custom dtype that describes a color as four unsigned bytes (RGBA) (★☆☆)\n\n< h23\nhint: np.dtype\n\n< a23\ncolor = np.dtype([(\"r\", np.ubyte),\n                  (\"g\", np.ubyte),\n                  (\"b\", np.ubyte),\n                  (\"a\", np.ubyte)])\n\n< q24\nMultiply a 5x3 matrix by a 3x2 matrix (real matrix product) (★☆☆)\n\n< h24\nhint:\n\n< a24\nZ = np.matmul(np.ones((5, 3)), np.ones((3, 2)))\nprint(Z)\n\n# Alternative solution, in Python 3.5 and above\nZ = np.ones((5,3)) @ np.ones((3,2))\nprint(Z)\n\n< q25\nGiven a 1D array, negate all elements which are between 3 and 8, in place. (★☆☆)\n\n< h25\nhint: >, <\n\n< a25\n# Author: Evgeni Burovski\n\nZ = np.arange(11)\nZ[(3 < Z) & (Z < 8)] *= -1\nprint(Z)\n\n< q26\nWhat is the output of the following script? (★☆☆)\n```python\n# Author: Jake VanderPlas\n\nprint(sum(range(5),-1))\nfrom numpy import *\nprint(sum(range(5),-1))\n```\n\n< h26\nhint: np.sum\n\n< a26\n# Author: Jake VanderPlas\n\nprint(sum(range(5),-1))\nfrom numpy import *\nprint(sum(range(5),-1))\n\n< q27\nConsider an integer vector Z, which of these expressions are legal? (★☆☆)\n```python\nZ**Z\n2 << Z >> 2\nZ <- Z\n1j*Z\nZ/1/1\nZ<Z>Z\n```\n\n< h27\nNo hints provided...\n\n< a27\nZ**Z\n2 << Z >> 2\nZ <- Z\n1j*Z\nZ/1/1\nZ<Z>Z\n\n< q28\nWhat are the result of the following expressions? (★☆☆)\n```python\nnp.array(0) / np.array(0)\nnp.array(0) // np.array(0)\nnp.array([np.nan]).astype(int).astype(float)\n```\n\n< h28\nNo hints provided...\n\n< a28\nprint(np.array(0) / np.array(0))\nprint(np.array(0) // np.array(0))\nprint(np.array([np.nan]).astype(int).astype(float))\n\n< q29\nHow to round away from zero a float array ? (★☆☆)\n\n< h29\nhint: np.uniform, np.copysign, np.ceil, np.abs, np.where\n\n< a29\n# Author: Charles R Harris\n\nZ = np.random.uniform(-10,+10,10)\nprint(np.copysign(np.ceil(np.abs(Z)), Z))\n\n# More readable but less efficient\nprint(np.where(Z>0, np.ceil(Z), np.floor(Z)))\n\n< q30\nHow to find common values between two arrays? (★☆☆)\n\n< h30\nhint: np.intersect1d\n\n< a30\nZ1 = np.random.randint(0,10,10)\nZ2 = np.random.randint(0,10,10)\nprint(np.intersect1d(Z1,Z2))\n\n< q31\nHow to ignore all numpy warnings (not recommended)? (★☆☆)\n\n< h31\nhint: np.seterr, np.errstate\n\n< a31\n# Suicide mode on\ndefaults = np.seterr(all=\"ignore\")\nZ = np.ones(1) / 0\n\n# Back to sanity\n_ = np.seterr(**defaults)\n\n# Equivalently with a context manager\nwith np.errstate(all=\"ignore\"):\n    np.arange(3) / 0\n\n< q32\nIs the following expressions true? (★☆☆)\n```python\nnp.sqrt(-1) == np.emath.sqrt(-1)\n```\n\n< h32\nhint: imaginary number\n\n< a32\nnp.sqrt(-1) == np.emath.sqrt(-1)\n\n< q33\nHow to get the dates of yesterday, today and tomorrow? (★☆☆)\n\n< h33\nhint: np.datetime64, np.timedelta64\n\n< a33\nyesterday = np.datetime64('today') - np.timedelta64(1)\ntoday     = np.datetime64('today')\ntomorrow  = np.datetime64('today') + np.timedelta64(1)\n\n< q34\nHow to get all the dates corresponding to the month of July 2016? (★★☆)\n\n< h34\nhint: np.arange(dtype=datetime64['D'])\n\n< a34\nZ = np.arange('2016-07', '2016-08', dtype='datetime64[D]')\nprint(Z)\n\n< q35\nHow to compute ((A+B)*(-A/2)) in place (without copy)? (★★☆)\n\n< h35\nhint: np.add(out=), np.negative(out=), np.multiply(out=), np.divide(out=)\n\n< a35\nA = np.ones(3)*1\nB = np.ones(3)*2\nnp.add(A,B,out=B)\nnp.divide(A,2,out=A)\nnp.negative(A,out=A)\nnp.multiply(A,B,out=A)\n\n< q36\nExtract the integer part of a random array of positive numbers using 4 different methods (★★☆)\n\n< h36\nhint: %, np.floor, astype, np.trunc\n\n< a36\nZ = np.random.uniform(0,10,10)\n\nprint(Z - Z%1)\nprint(Z // 1)\nprint(np.floor(Z))\nprint(Z.astype(int))\nprint(np.trunc(Z))\n\n< q37\nCreate a 5x5 matrix with row values ranging from 0 to 4 (★★☆)\n\n< h37\nhint: np.arange\n\n< a37\nZ = np.zeros((5,5))\nZ += np.arange(5)\nprint(Z)\n\n# without broadcasting\nZ = np.tile(np.arange(0, 5), (5,1))\nprint(Z)\n\n< q38\nConsider a generator function that generates 10 integers and use it to build an array (★☆☆)\n\n< h38\nhint: np.fromiter\n\n< a38\ndef generate():\n    for x in range(10):\n        yield x\nZ = np.fromiter(generate(),dtype=float,count=-1)\nprint(Z)\n\n< q39\nCreate a vector of size 10 with values ranging from 0 to 1, both excluded (★★☆)\n\n< h39\nhint: np.linspace\n\n< a39\nZ = np.linspace(0,1,11,endpoint=False)[1:]\nprint(Z)\n\n< q40\nCreate a random vector of size 10 and sort it (★★☆)\n\n< h40\nhint: sort\n\n< a40\nZ = np.random.random(10)\nZ.sort()\nprint(Z)\n\n< q41\nHow to sum a small array faster than np.sum? (★★☆)\n\n< h41\nhint: np.add.reduce\n\n< a41\n# Author: Evgeni Burovski\n\nZ = np.arange(10)\nnp.add.reduce(Z)\n\n< q42\nConsider two random arrays A and B, check if they are equal (★★☆)\n\n< h42\nhint: np.allclose, np.array_equal\n\n< a42\nA = np.random.randint(0,2,5)\nB = np.random.randint(0,2,5)\n\n# Assuming identical shape of the arrays and a tolerance for the comparison of values\nequal = np.allclose(A,B)\nprint(equal)\n\n# Checking both the shape and the element values, no tolerance (values have to be exactly equal)\nequal = np.array_equal(A,B)\nprint(equal)\n\n< q43\nMake an array immutable (read-only) (★★☆)\n\n< h43\nhint: flags.writeable\n\n< a43\nZ = np.zeros(10)\nZ.flags.writeable = False\nZ[0] = 1\n\n< q44\nConsider a random 10x2 matrix representing cartesian coordinates, convert them to polar coordinates (★★☆)\n\n< h44\nhint: np.sqrt, np.arctan2\n\n< a44\nZ = np.random.random((10,2))\nX,Y = Z[:,0], Z[:,1]\nR = np.sqrt(X**2+Y**2)\nT = np.arctan2(Y,X)\nprint(R)\nprint(T)\n\n< q45\nCreate random vector of size 10 and replace the maximum value by 0 (★★☆)\n\n< h45\nhint: argmax\n\n< a45\nZ = np.random.random(10)\nZ[Z.argmax()] = 0\nprint(Z)\n\n< q46\nCreate a structured array with `x` and `y` coordinates covering the [0,1]x[0,1] area (★★☆)\n\n< h46\nhint: np.meshgrid\n\n< a46\nZ = np.zeros((5,5), [('x',float),('y',float)])\nZ['x'], Z['y'] = np.meshgrid(np.linspace(0,1,5),\n                             np.linspace(0,1,5))\nprint(Z)\n\n< q47\nGiven two arrays, X and Y, construct the Cauchy matrix C (Cij =1/(xi - yj)) (★★☆)\n\n< h47\nhint: np.subtract.outer\n\n< a47\n# Author: Evgeni Burovski\n\nX = np.arange(8)\nY = X + 0.5\nC = 1.0 / np.subtract.outer(X, Y)\nprint(np.linalg.det(C))\n\n< q48\nPrint the minimum and maximum representable values for each numpy scalar type (★★☆)\n\n< h48\nhint: np.iinfo, np.finfo, eps\n\n< a48\nfor dtype in [np.int8, np.int32, np.int64]:\n   print(np.iinfo(dtype).min)\n   print(np.iinfo(dtype).max)\nfor dtype in [np.float32, np.float64]:\n   print(np.finfo(dtype).min)\n   print(np.finfo(dtype).max)\n   print(np.finfo(dtype).eps)\n\n< q49\nHow to print all the values of an array? (★★☆)\n\n< h49\nhint: np.set_printoptions\n\n< a49\nnp.set_printoptions(threshold=float(\"inf\"))\nZ = np.zeros((40,40))\nprint(Z)\n\n< q50\nHow to find the closest value (to a given scalar) in a vector? (★★☆)\n\n< h50\nhint: argmin\n\n< a50\nZ = np.arange(100)\nv = np.random.uniform(0,100)\nindex = (np.abs(Z-v)).argmin()\nprint(Z[index])\n\n< q51\nCreate a structured array representing a position (x,y) and a color (r,g,b) (★★☆)\n\n< h51\nhint: dtype\n\n< a51\nZ = np.zeros(10, [ ('position', [ ('x', float, 1),\n                                  ('y', float, 1)]),\n                   ('color',    [ ('r', float, 1),\n                                  ('g', float, 1),\n                                  ('b', float, 1)])])\nprint(Z)\n\n< q52\nConsider a random vector with shape (100,2) representing coordinates, find point by point distances (★★☆)\n\n< h52\nhint: np.atleast_2d, T, np.sqrt\n\n< a52\nZ = np.random.random((10,2))\nX,Y = np.atleast_2d(Z[:,0], Z[:,1])\nD = np.sqrt( (X-X.T)**2 + (Y-Y.T)**2)\nprint(D)\n\n# Much faster with scipy\nimport scipy\n# Thanks Gavin Heverly-Coulson (#issue 1)\nimport scipy.spatial\n\nZ = np.random.random((10,2))\nD = scipy.spatial.distance.cdist(Z,Z)\nprint(D)\n\n< q53\nHow to convert a float (32 bits) array into an integer (32 bits) array in place?\n\n< h53\nhint: view and [:] =\n\n< a53\n# Thanks Vikas (https://stackoverflow.com/a/10622758/5989906)\n# & unutbu (https://stackoverflow.com/a/4396247/5989906)\nZ = (np.random.rand(10)*100).astype(np.float32)\nY = Z.view(np.int32)\nY[:] = Z\nprint(Y)\n\n< q54\nHow to read the following file? (★★☆)\n```\n1, 2, 3, 4, 5\n6,  ,  , 7, 8\n ,  , 9,10,11\n```\n\n< h54\nhint: np.genfromtxt\n\n< a54\nfrom io import StringIO\n\n# Fake file\ns = StringIO('''1, 2, 3, 4, 5\n\n                6,  ,  , 7, 8\n\n                 ,  , 9,10,11\n''')\nZ = np.genfromtxt(s, delimiter=\",\", dtype = int, filling_values = 0)\nprint(Z)\n\n< q55\nWhat is the equivalent of enumerate for numpy arrays? (★★☆)\n\n< h55\nhint: np.ndenumerate, np.ndindex\n\n< a55\nZ = np.arange(9).reshape(3,3)\nfor index, value in np.ndenumerate(Z):\n    print(index, value)\nfor index in np.ndindex(Z.shape):\n    print(index, Z[index])\n\n< q56\nGenerate a generic 2D Gaussian-like array (★★☆)\n\n< h56\nhint: np.meshgrid, np.exp\n\n< a56\nX, Y = np.meshgrid(np.linspace(-1,1,10), np.linspace(-1,1,10))\nD = np.sqrt(X*X+Y*Y)\nsigma, mu = 1.0, 0.0\nG = np.exp(-( (D-mu)**2 / ( 2.0 * sigma**2 ) ) )\nprint(G)\n\n< q57\nHow to randomly place p elements in a 2D array? (★★☆)\n\n< h57\nhint: np.put, np.random.choice\n\n< a57\n# Author: Divakar\n\nn = 10\np = 3\nZ = np.zeros((n,n))\nnp.put(Z, np.random.choice(range(n*n), p, replace=False),1)\nprint(Z)\n\n< q58\nSubtract the mean of each row of a matrix (★★☆)\n\n< h58\nhint: mean(axis=,keepdims=)\n\n< a58\n# Author: Warren Weckesser\n\nX = np.random.rand(5, 10)\n\n# Recent versions of numpy\nY = X - X.mean(axis=1, keepdims=True)\n\n# Older versions of numpy\nY = X - X.mean(axis=1).reshape(-1, 1)\n\nprint(Y)\n\n< q59\nHow to sort an array by the nth column? (★★☆)\n\n< h59\nhint: argsort\n\n< a59\n# Author: Steve Tjoa\n\nZ = np.random.randint(0,10,(3,3))\nprint(Z)\nprint(Z[Z[:,1].argsort()])\n\n< q60\nHow to tell if a given 2D array has null columns? (★★☆)\n\n< h60\nhint: any, ~\n\n< a60\n# Author: Warren Weckesser\n\n# null : 0 \nZ = np.random.randint(0,3,(3,10))\nprint((~Z.any(axis=0)).any())\n\n# null : np.nan\nZ=np.array([\n    [0,1,np.nan],\n    [1,2,np.nan],\n    [4,5,np.nan]\n])\nprint(np.isnan(Z).all(axis=0))\n\n< q61\nFind the nearest value from a given value in an array (★★☆)\n\n< h61\nhint: np.abs, argmin, flat\n\n< a61\nZ = np.random.uniform(0,1,10)\nz = 0.5\nm = Z.flat[np.abs(Z - z).argmin()]\nprint(m)\n\n< q62\nConsidering two arrays with shape (1,3) and (3,1), how to compute their sum using an iterator? (★★☆)\n\n< h62\nhint: np.nditer\n\n< a62\nA = np.arange(3).reshape(3,1)\nB = np.arange(3).reshape(1,3)\nit = np.nditer([A,B,None])\nfor x,y,z in it: z[...] = x + y\nprint(it.operands[2])\n\n< q63\nCreate an array class that has a name attribute (★★☆)\n\n< h63\nhint: class method\n\n< a63\nclass 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.name = getattr(obj, 'name', \"no name\")\n\nZ = NamedArray(np.arange(10), \"range_10\")\nprint (Z.name)\n\n< q64\nConsider a given vector, how to add 1 to each element indexed by a second vector (be careful with repeated indices)? (★★★)\n\n< h64\nhint: np.bincount | np.add.at\n\n< a64\n# Author: Brett Olsen\n\nZ = np.ones(10)\nI = np.random.randint(0,len(Z),20)\nZ += np.bincount(I, minlength=len(Z))\nprint(Z)\n\n# Another solution\n# Author: Bartosz Telenczuk\nnp.add.at(Z, I, 1)\nprint(Z)\n\n< q65\nHow to accumulate elements of a vector (X) to an array (F) based on an index list (I)? (★★★)\n\n< h65\nhint: np.bincount\n\n< a65\n# Author: Alan G Isaac\n\nX = [1,2,3,4,5,6]\nI = [1,3,9,3,4,1]\nF = np.bincount(I,X)\nprint(F)\n\n< q66\nConsidering a (w,h,3) image of (dtype=ubyte), compute the number of unique colors (★★☆)\n\n< h66\nhint: np.unique\n\n< a66\n# Author: Fisher Wang\n\nw, h = 256, 256\nI = np.random.randint(0, 4, (h, w, 3)).astype(np.ubyte)\ncolors = np.unique(I.reshape(-1, 3), axis=0)\nn = len(colors)\nprint(n)\n\n# Faster version\n# Author: Mark Setchell\n# https://stackoverflow.com/a/59671950/2836621\n\nw, h = 256, 256\nI = np.random.randint(0,4,(h,w,3), dtype=np.uint8)\n\n# View each pixel as a single 24-bit integer, rather than three 8-bit bytes\nI24 = np.dot(I.astype(np.uint32),[1,256,65536])\n\n# Count unique colours\nn = len(np.unique(I24))\nprint(n)\n\n< q67\nConsidering a four dimensions array, how to get sum over the last two axis at once? (★★★)\n\n< h67\nhint: sum(axis=(-2,-1))\n\n< a67\nA = np.random.randint(0,10,(3,4,3,4))\n# solution by passing a tuple of axes (introduced in numpy 1.7.0)\nsum = A.sum(axis=(-2,-1))\nprint(sum)\n# solution by flattening the last two dimensions into one\n# (useful for functions that don't accept tuples for axis argument)\nsum = A.reshape(A.shape[:-2] + (-1,)).sum(axis=-1)\nprint(sum)\n\n< q68\nConsidering a one-dimensional vector D, how to compute means of subsets of D using a vector S of same size describing subset  indices? (★★★)\n\n< h68\nhint: np.bincount\n\n< a68\n# Author: Jaime Fernández del Río\n\nD = np.random.uniform(0,1,100)\nS = np.random.randint(0,10,100)\nD_sums = np.bincount(S, weights=D)\nD_counts = np.bincount(S)\nD_means = D_sums / D_counts\nprint(D_means)\n\n# Pandas solution as a reference due to more intuitive code\nimport pandas as pd\nprint(pd.Series(D).groupby(S).mean())\n\n< q69\nHow to get the diagonal of a dot product? (★★★)\n\n< h69\nhint: np.diag\n\n< a69\n# Author: Mathieu Blondel\n\nA = np.random.uniform(0,1,(5,5))\nB = np.random.uniform(0,1,(5,5))\n\n# Slow version\nnp.diag(np.dot(A, B))\n\n# Fast version\nnp.sum(A * B.T, axis=1)\n\n# Faster version\nnp.einsum(\"ij,ji->i\", A, B)\n\n< q70\nConsider the vector [1, 2, 3, 4, 5], how to build a new vector with 3 consecutive zeros interleaved between each value? (★★★)\n\n< h70\nhint: array[::4]\n\n< a70\n# Author: Warren Weckesser\n\nZ = np.array([1,2,3,4,5])\nnz = 3\nZ0 = np.zeros(len(Z) + (len(Z)-1)*(nz))\nZ0[::nz+1] = Z\nprint(Z0)\n\n< q71\nConsider an array of dimension (5,5,3), how to multiply it by an array with dimensions (5,5)? (★★★)\n\n< h71\nhint: array[:, :, None]\n\n< a71\nA = np.ones((5,5,3))\nB = 2*np.ones((5,5))\nprint(A * B[:,:,None])\n\n< q72\nHow to swap two rows of an array? (★★★)\n\n< h72\nhint: array[[]] = array[[]]\n\n< a72\n# Author: Eelco Hoogendoorn\n\nA = np.arange(25).reshape(5,5)\nA[[0,1]] = A[[1,0]]\nprint(A)\n\n< q73\nConsider a set of 10 triplets describing 10 triangles (with shared vertices), find the set of unique line segments composing all the  triangles (★★★)\n\n< h73\nhint: repeat, np.roll, np.sort, view, np.unique\n\n< a73\n# Author: Nicolas P. Rougier\n\nfaces = np.random.randint(0,100,(10,3))\nF = np.roll(faces.repeat(2,axis=1),-1,axis=1)\nF = F.reshape(len(F)*3,2)\nF = np.sort(F,axis=1)\nG = F.view( dtype=[('p0',F.dtype),('p1',F.dtype)] )\nG = np.unique(G)\nprint(G)\n\n< q74\nGiven a sorted array C that corresponds to a bincount, how to produce an array A such that np.bincount(A) == C? (★★★)\n\n< h74\nhint: np.repeat\n\n< a74\n# Author: Jaime Fernández del Río\n\nC = np.bincount([1,1,2,3,4,4,6])\nA = np.repeat(np.arange(len(C)), C)\nprint(A)\n\n< q75\nHow to compute averages using a sliding window over an array? (★★★)\n\n< h75\nhint: np.cumsum, from numpy.lib.stride_tricks import sliding_window_view (np>=1.20.0)\n\n< a75\n# Author: Jaime Fernández del Río\n\ndef 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\nZ = np.arange(20)\nprint(moving_average(Z, n=3))\n\n# Author: Jeff Luo (@Jeff1999)\n# make sure your NumPy >= 1.20.0\n\nfrom numpy.lib.stride_tricks import sliding_window_view\n\nZ = np.arange(20)\nprint(sliding_window_view(Z, window_shape=3).mean(axis=-1))\n\n< q76\nConsider 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]) (★★★)\n\n< h76\nhint: from numpy.lib import stride_tricks, from numpy.lib.stride_tricks import sliding_window_view (np>=1.20.0)\n\n< a76\n# Author: Joe Kington / Erik Rigtorp\nfrom numpy.lib import stride_tricks\n\ndef rolling(a, window):\n    shape = (a.size - window + 1, window)\n    strides = (a.strides[0], a.strides[0])\n    return stride_tricks.as_strided(a, shape=shape, strides=strides)\nZ = rolling(np.arange(10), 3)\nprint(Z)\n\n# Author: Jeff Luo (@Jeff1999)\n\nZ = np.arange(10)\nprint(sliding_window_view(Z, window_shape=3))\n\n< q77\nHow to negate a boolean, or to change the sign of a float inplace? (★★★)\n\n< h77\nhint: np.logical_not, np.negative\n\n< a77\n# Author: Nathaniel J. Smith\n\nZ = np.random.randint(0,2,100)\nnp.logical_not(Z, out=Z)\n\nZ = np.random.uniform(-1.0,1.0,100)\nnp.negative(Z, out=Z)\n\n< q78\nConsider 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])? (★★★)\n\n< h78\nNo hints provided...\n\n< a78\nP0 = np.random.uniform(-10,10,(10,2))\nP1 = np.random.uniform(-10,10,(10,2))\np  = np.random.uniform(-10,10,( 1,2))\n\ndef distance_faster(P0,P1,p):\n    #Author: Hemanth Pasupuleti\n    #Reference: https://mathworld.wolfram.com/Point-LineDistance2-Dimensional.html\n\n    v = P1- P0 \n    v[:,[0,1]] = v[:,[1,0]]\n    v[:,1]*=-1 \n    norm = np.linalg.norm(v,axis=1)   \n    r = P0 - p\n    d = np.abs(np.einsum(\"ij,ij->i\",r,v)) / norm \n\n    return d\n\nprint(distance_faster(P0, P1, p))\n\n##--------------- OR ---------------##\ndef distance_slower(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\nprint(distance_slower(P0, P1, p))\n\n< q79\nConsider 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])? (★★★)\n\n< h79\nNo hints provided...\n\n< a79\n# Author: Italmassov Kuanysh\n\n# based on distance function from previous question\nP0 = np.random.uniform(-10, 10, (10,2))\nP1 = np.random.uniform(-10,10,(10,2))\np = np.random.uniform(-10, 10, (10,2))\nprint(np.array([distance(P0,P1,p_i) for p_i in p]))\n\n# Author: Yang Wu (Broadcasting)\ndef distance_points_to_lines(p: np.ndarray, p_1: np.ndarray, p_2: np.ndarray) -> np.ndarray:\n    x_0, y_0 = p.T  # Shape -> (n points, )\n    x_1, y_1 = p_1.T  # Shape -> (n lines, )\n    x_2, y_2 = p_2.T  # Shape -> (n lines, )\n\n    # Displacement vector coordinates from p_1 -> p_2\n    dx = x_2 - x_1  # Shape -> (n lines, )\n    dy = y_2 - y_1  # Shape -> (n lines, )\n\n    # The 'cross product' term\n    cross_term = x_2 * y_1 - y_2 * x_1  # Shape -> (n lines, )\n\n    # Broadcast x_0, y_0 (n points, 1) and dx, dy, cross_term (1, n lines) -> (n points, n lines)\n    numerator = np.abs(\n        dy[np.newaxis, :] * x_0[:, np.newaxis]\n        - dx[np.newaxis, :] * y_0[:, np.newaxis]\n        + cross_term[np.newaxis, :]\n    )\n    denominator = np.sqrt(dx**2 + dy**2)  # Shape -> (n lines, )\n\n    # Shape (n points, n lines) / (1, n_lines) -> (n points, n lines)\n    return numerator / denominator[np.newaxis, :]\n\ndistance_points_to_lines(p, P0, P1)\n\n< q80\nConsider an arbitrary array, write a function that extracts a subpart with a fixed shape and centered on a given element (pad with a `fill` value when necessary) (★★★)\n\n< h80\nhint: minimum maximum\n\n< a80\n# Author: Nicolas Rougier\n\nZ = np.random.randint(0,10,(10,10))\nshape = (5,5)\nfill  = 0\nposition = (1,1)\n\nR = np.ones(shape, dtype=Z.dtype)*fill\nP  = np.array(list(position)).astype(int)\nRs = np.array(list(R.shape)).astype(int)\nZs = np.array(list(Z.shape)).astype(int)\n\nR_start = np.zeros((len(shape),)).astype(int)\nR_stop  = np.array(list(shape)).astype(int)\nZ_start = (P-Rs//2)\nZ_stop  = (P+Rs//2)+Rs%2\n\nR_start = (R_start - np.minimum(Z_start,0)).tolist()\nZ_start = (np.maximum(Z_start,0)).tolist()\nR_stop = np.maximum(R_start, (R_stop - np.maximum(Z_stop-Zs,0))).tolist()\nZ_stop = (np.minimum(Z_stop,Zs)).tolist()\n\nr = tuple([slice(start,stop) for start,stop in zip(R_start,R_stop)])\nz = tuple([slice(start,stop) for start,stop in zip(Z_start,Z_stop)])\nR[r] = Z[z]\nprint(Z)\nprint(R)\n\n< q81\nConsider 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]]? (★★★)\n\n< h81\nhint: stride_tricks.as_strided, from numpy.lib.stride_tricks import sliding_window_view (np>=1.20.0)\n\n< a81\n# Author: Stefan van der Walt\n\nZ = np.arange(1,15,dtype=np.uint32)\nR = stride_tricks.as_strided(Z,(11,4),(4,4))\nprint(R)\n\n# Author: Jeff Luo (@Jeff1999)\n\nZ = np.arange(1, 15, dtype=np.uint32)\nprint(sliding_window_view(Z, window_shape=4))\n\n< q82\nCompute a matrix rank (★★★)\n\n< h82\nhint: np.linalg.svd, np.linalg.matrix_rank\n\n< a82\n# Author: Stefan van der Walt\n\nZ = np.random.uniform(0,1,(10,10))\nU, S, V = np.linalg.svd(Z) # Singular Value Decomposition\nthreshold = len(S) * S.max() * np.finfo(S.dtype).eps\nrank = np.sum(S > threshold)\nprint(rank)\n\n# alternative solution:\n# Author: Jeff Luo (@Jeff1999)\n\nrank = np.linalg.matrix_rank(Z)\nprint(rank)\n\n< q83\nHow to find the most frequent value in an array?\n\n< h83\nhint: np.bincount, argmax\n\n< a83\nZ = np.random.randint(0,10,50)\nprint(np.bincount(Z).argmax())\n\n< q84\nExtract all the contiguous 3x3 blocks from a random 10x10 matrix (★★★)\n\n< h84\nhint: stride_tricks.as_strided, from numpy.lib.stride_tricks import sliding_window_view (np>=1.20.0)\n\n< a84\n# Author: Chris Barker\n\nZ = np.random.randint(0,5,(10,10))\nn = 3\ni = 1 + (Z.shape[0]-3)\nj = 1 + (Z.shape[1]-3)\nC = stride_tricks.as_strided(Z, shape=(i, j, n, n), strides=Z.strides + Z.strides)\nprint(C)\n\n# Author: Jeff Luo (@Jeff1999)\n\nZ = np.random.randint(0,5,(10,10))\nprint(sliding_window_view(Z, window_shape=(3, 3)))\n\n< q85\nCreate a 2D array subclass such that Z[i,j] == Z[j,i] (★★★)\n\n< h85\nhint: class method\n\n< a85\n# Author: Eric O. Lebigot\n# Note: only works for 2d array and value setting using indices\n\nclass 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\ndef symetric(Z):\n    return np.asarray(Z + Z.T - np.diag(Z.diagonal())).view(Symetric)\n\nS = symetric(np.random.randint(0,10,(5,5)))\nS[2,3] = 42\nprint(S)\n\n< q86\nConsider a set of p matrices with 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)) (★★★)\n\n< h86\nhint: np.tensordot\n\n< a86\n# Author: Stefan van der Walt\n\np, n = 10, 20\nM = np.ones((p,n,n))\nV = np.ones((p,n,1))\nS = np.tensordot(M, V, axes=[[0, 2], [0, 1]])\nprint(S)\n\n# It works, because:\n# M is (p,n,n)\n# V is (p,n,1)\n# Thus, summing over the paired axes 0 and 0 (of M and V independently),\n# and 2 and 1, to remain with a (n,1) vector.\n\n< q87\nConsider a 16x16 array, how to get the block-sum (block size is 4x4)? (★★★)\n\n< h87\nhint: np.add.reduceat, from numpy.lib.stride_tricks import sliding_window_view (np>=1.20.0)\n\n< a87\n# Author: Robert Kern\n\nZ = np.ones((16,16))\nk = 4\nS = 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)\nprint(S)\n\n# alternative solution:\n# Author: Sebastian Wallkötter (@FirefoxMetzger)\n\nZ = np.ones((16,16))\nk = 4\n\nwindows = np.lib.stride_tricks.sliding_window_view(Z, (k, k))\nS = windows[::k, ::k, ...].sum(axis=(-2, -1))\n\n# alternative solution (by @Gattocrucco)\nS = Z.reshape(4, 4, 4, 4).sum((1, 3))\n\n< q88\nHow to implement the Game of Life using numpy arrays? (★★★)\n\n< h88\nNo hints provided...\n\n< a88\n# Author: Nicolas Rougier\n\ndef 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\nZ = np.random.randint(0,2,(50,50))\nfor i in range(100): Z = iterate(Z)\nprint(Z)\n\n< q89\nHow to get the n largest values of an array (★★★)\n\n< h89\nhint: np.argsort | np.argpartition\n\n< a89\nZ = np.arange(10000)\nnp.random.shuffle(Z)\nn = 5\n\n# Slow\nprint (Z[np.argsort(Z)[-n:]])\n\n# Fast\nprint (Z[np.argpartition(-Z,n)[:n]])\n\n< q90\nGiven an arbitrary number of vectors, build the cartesian product (every combination of every item) (★★★)\n\n< h90\nhint: np.indices\n\n< a90\n# Author: Stefan Van der Walt\n\ndef 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\nprint (cartesian(([1, 2, 3], [4, 5], [6, 7])))\n\n< q91\nHow to create a record array from a regular array? (★★★)\n\n< h91\nhint: np.core.records.fromarrays\n\n< a91\nZ = np.array([(\"Hello\", 2.5, 3),\n              (\"World\", 3.6, 2)])\nR = np.core.records.fromarrays(Z.T,\n                               names='col1, col2, col3',\n                               formats = 'S8, f8, i8')\nprint(R)\n\n< q92\nConsider a large vector Z, compute Z to the power of 3 using 3 different methods (★★★)\n\n< h92\nhint: np.power, *, np.einsum\n\n< a92\n# Author: Ryan G.\n\nx = np.random.rand(int(5e7))\n\n%timeit np.power(x,3)\n%timeit x*x*x\n%timeit np.einsum('i,i,i->i',x,x,x)\n\n< q93\nConsider 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? (★★★)\n\n< h93\nhint: np.where\n\n< a93\n# Author: Gabe Schwartz\n\nA = np.random.randint(0,5,(8,3))\nB = np.random.randint(0,5,(2,2))\n\nC = (A[..., np.newaxis, np.newaxis] == B)\nrows = np.where(C.any((3,1)).all(1))[0]\nprint(rows)\n\n< q94\nConsidering a 10x3 matrix, extract rows with unequal values (e.g. [2,2,3]) (★★★)\n\n< h94\nNo hints provided...\n\n< a94\n# Author: Robert Kern\n\nZ = np.random.randint(0,5,(10,3))\nprint(Z)\n# solution for arrays of all dtypes (including string arrays and record arrays)\nE = np.all(Z[:,1:] == Z[:,:-1], axis=1)\nU = Z[~E]\nprint(U)\n# soluiton for numerical arrays only, will work for any number of columns in Z\nU = Z[Z.max(axis=1) != Z.min(axis=1),:]\nprint(U)\n\n< q95\nConvert a vector of ints into a matrix binary representation (★★★)\n\n< h95\nhint: np.unpackbits\n\n< a95\n# Author: Warren Weckesser\n\nI = np.array([0, 1, 2, 3, 15, 16, 32, 64, 128])\nB = ((I.reshape(-1,1) & (2**np.arange(8))) != 0).astype(int)\nprint(B[:,::-1])\n\n# Author: Daniel T. McDonald\n\nI = np.array([0, 1, 2, 3, 15, 16, 32, 64, 128], dtype=np.uint8)\nprint(np.unpackbits(I[:, np.newaxis], axis=1))\n\n< q96\nGiven a two dimensional array, how to extract unique rows? (★★★)\n\n< h96\nhint: np.ascontiguousarray | np.unique\n\n< a96\n# Author: Jaime Fernández del Río\n\nZ = np.random.randint(0,2,(6,3))\nT = np.ascontiguousarray(Z).view(np.dtype((np.void, Z.dtype.itemsize * Z.shape[1])))\n_, idx = np.unique(T, return_index=True)\nuZ = Z[idx]\nprint(uZ)\n\n# Author: Andreas Kouzelis\n# NumPy >= 1.13\nuZ = np.unique(Z, axis=0)\nprint(uZ)\n\n< q97\nConsidering 2 vectors A & B, write the einsum equivalent of inner, outer, sum, and mul function (★★★)\n\n< h97\nhint: np.einsum\n\n< a97\n# Author: Alex Riley\n# Make sure to read: http://ajcr.net/Basic-guide-to-einsum/\n\nA = np.random.uniform(0,1,10)\nB = np.random.uniform(0,1,10)\n\nnp.einsum('i->', A)       # np.sum(A)\nnp.einsum('i,i->i', A, B) # A * B\nnp.einsum('i,i', A, B)    # np.inner(A, B)\nnp.einsum('i,j->ij', A, B)    # np.outer(A, B)\n\n< q98\nConsidering a path described by two vectors (X,Y), how to sample it using equidistant samples (★★★)?\n\n< h98\nhint: np.cumsum, np.interp\n\n< a98\n# Author: Bas Swinckels\n\nphi = np.arange(0, 10*np.pi, 0.1)\na = 1\nx = a*phi*np.cos(phi)\ny = a*phi*np.sin(phi)\n\ndr = (np.diff(x)**2 + np.diff(y)**2)**.5 # segment lengths\nr = np.zeros_like(x)\nr[1:] = np.cumsum(dr)                # integrate path\nr_int = np.linspace(0, r.max(), 200) # regular spaced path\nx_int = np.interp(r_int, r, x)       # integrate path\ny_int = np.interp(r_int, r, y)\n\n< q99\nGiven 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. (★★★)\n\n< h99\nhint: np.logical_and.reduce, np.mod\n\n< a99\n# Author: Evgeni Burovski\n\nX = 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]])\nn = 4\nM = np.logical_and.reduce(np.mod(X, 1) == 0, axis=-1)\nM &= (X.sum(axis=-1) == n)\nprint(X[M])\n\n< q100\nCompute 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). (★★★)\n\n< h100\nhint: np.percentile\n\n< a100\n# Author: Jessica B. Hamrick\n\nX = np.random.randn(100) # random 1D array\nN = 1000 # number of bootstrap samples\nidx = np.random.randint(0, X.size, (N, X.size))\nmeans = X[idx].mean(axis=1)\nconfint = np.percentile(means, [2.5, 97.5])\nprint(confint)\n"
  },
  {
    "path": "source/headers.ktx",
    "content": "< header\n# 100 numpy exercises\n\nThis is a collection of exercises that have been collected in the numpy mailing list, on stack overflow\nand in the numpy documentation. The goal of this collection is to offer a quick reference for both old\nand new users but also to provide a set of exercises for those who teach.\n\n\nIf you find an error or think you've a better way to solve some of them, feel\nfree to open an issue at <https://github.com/rougier/numpy-100>.\n\n\n< sub_header\nFile automatically generated. See the documentation to update questions/answers/hints programmatically.\n\n\n< jupyter_instruction\nRun the `initialise.py` module, then for each question you can query the\nanswer or an hint with `hint(n)` or `answer(n)` for `n` question number.\n\n\n< jupyter_instruction_rand\nRun the `initialise.py` module, then call a random question with `pick()` an hint towards its solution with\n`hint(n)` and the answer with `answer(n)`, where n is the number of the picked question.\n\n"
  }
]