├── .gitattributes ├── .github ├── FUNDING.yml └── workflows │ └── generate_solutions_files.yml ├── .gitignore ├── 100_Numpy_exercises.ipynb ├── 100_Numpy_exercises.md ├── 100_Numpy_exercises_with_hints.md ├── 100_Numpy_exercises_with_hints_with_solutions.md ├── 100_Numpy_exercises_with_solutions.md ├── 100_Numpy_random.ipynb ├── LICENSE.txt ├── README.md ├── generators.py ├── initialise.py ├── requirements.txt ├── runtime.txt └── source ├── exercises100.ktx └── headers.ktx /.gitattributes: -------------------------------------------------------------------------------- 1 | *.md linguist-language=Python 2 | *.ipynb linguist-language=Python 3 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: rougier # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] 4 | -------------------------------------------------------------------------------- /.github/workflows/generate_solutions_files.yml: -------------------------------------------------------------------------------- 1 | name: Generate Solutions Files 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | paths: 8 | - source/exercises100.ktx 9 | 10 | jobs: 11 | generate_files: 12 | runs-on: ubuntu-22.04 # Python 3.7 is not supported on latest Ubuntu 13 | 14 | permissions: 15 | contents: write 16 | 17 | steps: 18 | - name: Checkout repository 19 | uses: actions/checkout@v4 20 | 21 | - name: Setup Python 22 | uses: actions/setup-python@v5 23 | with: 24 | python-version: '3.7' 25 | cache: 'pip' 26 | 27 | - name: Install dependencies 28 | run: pip3 install -r requirements.txt 29 | 30 | - name: Generate solutions files 31 | run: python3 generators.py 32 | 33 | - name: Set environment variables 34 | run: echo "SHA_SHORT=$(git rev-parse --short $GITHUB_SHA)" >> $GITHUB_ENV 35 | 36 | - name: Commit changes 37 | uses: stefanzweifel/git-auto-commit-action@v5 38 | with: 39 | commit_message: "solutions update from ${{ env.SHA_SHORT }}" 40 | file_pattern: > 41 | 100_Numpy_exercises.ipynb 42 | 100_Numpy_random.ipynb 43 | 100_Numpy_exercises.md 44 | 100_Numpy_exercises_with_hints.md 45 | 100_Numpy_exercises_with_hints_with_solutions.md 46 | 100_Numpy_exercises_with_solutions.md 47 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .ipynb_checkpoints/ 2 | __pycache__ 3 | venv 4 | .idea 5 | .vscode 6 | Untitled.ipynb 7 | -------------------------------------------------------------------------------- /100_Numpy_exercises.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "52249554", 6 | "metadata": {}, 7 | "source": [ 8 | "# 100 numpy exercises\n", 9 | "\n", 10 | "This is a collection of exercises that have been collected in the numpy mailing list, on stack overflow\n", 11 | "and in the numpy documentation. The goal of this collection is to offer a quick reference for both old\n", 12 | "and new users but also to provide a set of exercises for those who teach.\n", 13 | "\n", 14 | "\n", 15 | "If you find an error or think you've a better way to solve some of them, feel\n", 16 | "free to open an issue at ." 17 | ] 18 | }, 19 | { 20 | "cell_type": "markdown", 21 | "id": "9f0e56c3", 22 | "metadata": {}, 23 | "source": [ 24 | "File automatically generated. See the documentation to update questions/answers/hints programmatically." 25 | ] 26 | }, 27 | { 28 | "cell_type": "markdown", 29 | "id": "04b078a1", 30 | "metadata": {}, 31 | "source": [ 32 | "Run the `initialize.py` module, then for each question you can query the\n", 33 | "answer or an hint with `hint(n)` or `answer(n)` for `n` question number." 34 | ] 35 | }, 36 | { 37 | "cell_type": "code", 38 | "execution_count": null, 39 | "id": "63ebbf77", 40 | "metadata": {}, 41 | "outputs": [], 42 | "source": [ 43 | "%run initialise.py" 44 | ] 45 | }, 46 | { 47 | "cell_type": "markdown", 48 | "id": "e1672806", 49 | "metadata": {}, 50 | "source": [ 51 | "#### 1. Import the numpy package under the name `np` (★☆☆)" 52 | ] 53 | }, 54 | { 55 | "cell_type": "code", 56 | "execution_count": null, 57 | "id": "c39a5917", 58 | "metadata": {}, 59 | "outputs": [], 60 | "source": [] 61 | }, 62 | { 63 | "cell_type": "markdown", 64 | "id": "1d2a0271", 65 | "metadata": {}, 66 | "source": [ 67 | "#### 2. Print the numpy version and the configuration (★☆☆)" 68 | ] 69 | }, 70 | { 71 | "cell_type": "code", 72 | "execution_count": null, 73 | "id": "d4160594", 74 | "metadata": {}, 75 | "outputs": [], 76 | "source": [] 77 | }, 78 | { 79 | "cell_type": "markdown", 80 | "id": "4490d971", 81 | "metadata": {}, 82 | "source": [ 83 | "#### 3. Create a null vector of size 10 (★☆☆)" 84 | ] 85 | }, 86 | { 87 | "cell_type": "code", 88 | "execution_count": null, 89 | "id": "9b383fcc", 90 | "metadata": {}, 91 | "outputs": [], 92 | "source": [] 93 | }, 94 | { 95 | "cell_type": "markdown", 96 | "id": "4a217c03", 97 | "metadata": {}, 98 | "source": [ 99 | "#### 4. How to find the memory size of any array (★☆☆)" 100 | ] 101 | }, 102 | { 103 | "cell_type": "code", 104 | "execution_count": null, 105 | "id": "7f7c6497", 106 | "metadata": {}, 107 | "outputs": [], 108 | "source": [] 109 | }, 110 | { 111 | "cell_type": "markdown", 112 | "id": "4a412447", 113 | "metadata": {}, 114 | "source": [ 115 | "#### 5. How to get the documentation of the numpy add function from the command line? (★☆☆)" 116 | ] 117 | }, 118 | { 119 | "cell_type": "code", 120 | "execution_count": null, 121 | "id": "9b19b55d", 122 | "metadata": {}, 123 | "outputs": [], 124 | "source": [] 125 | }, 126 | { 127 | "cell_type": "markdown", 128 | "id": "8e890e32", 129 | "metadata": {}, 130 | "source": [ 131 | "#### 6. Create a null vector of size 10 but the fifth value which is 1 (★☆☆)" 132 | ] 133 | }, 134 | { 135 | "cell_type": "code", 136 | "execution_count": null, 137 | "id": "032ba316", 138 | "metadata": {}, 139 | "outputs": [], 140 | "source": [] 141 | }, 142 | { 143 | "cell_type": "markdown", 144 | "id": "36562b7f", 145 | "metadata": {}, 146 | "source": [ 147 | "#### 7. Create a vector with values ranging from 10 to 49 (★☆☆)" 148 | ] 149 | }, 150 | { 151 | "cell_type": "code", 152 | "execution_count": null, 153 | "id": "2f1ae242", 154 | "metadata": {}, 155 | "outputs": [], 156 | "source": [] 157 | }, 158 | { 159 | "cell_type": "markdown", 160 | "id": "d7d0e7ff", 161 | "metadata": {}, 162 | "source": [ 163 | "#### 8. Reverse a vector (first element becomes last) (★☆☆)" 164 | ] 165 | }, 166 | { 167 | "cell_type": "code", 168 | "execution_count": null, 169 | "id": "5a07c5c1", 170 | "metadata": {}, 171 | "outputs": [], 172 | "source": [] 173 | }, 174 | { 175 | "cell_type": "markdown", 176 | "id": "1fb509ab", 177 | "metadata": {}, 178 | "source": [ 179 | "#### 9. Create a 3x3 matrix with values ranging from 0 to 8 (★☆☆)" 180 | ] 181 | }, 182 | { 183 | "cell_type": "code", 184 | "execution_count": null, 185 | "id": "b4702eb8", 186 | "metadata": {}, 187 | "outputs": [], 188 | "source": [] 189 | }, 190 | { 191 | "cell_type": "markdown", 192 | "id": "0d0120c4", 193 | "metadata": {}, 194 | "source": [ 195 | "#### 10. Find indices of non-zero elements from [1,2,0,0,4,0] (★☆☆)" 196 | ] 197 | }, 198 | { 199 | "cell_type": "code", 200 | "execution_count": null, 201 | "id": "ead69303", 202 | "metadata": {}, 203 | "outputs": [], 204 | "source": [] 205 | }, 206 | { 207 | "cell_type": "markdown", 208 | "id": "c001c117", 209 | "metadata": {}, 210 | "source": [ 211 | "#### 11. Create a 3x3 identity matrix (★☆☆)" 212 | ] 213 | }, 214 | { 215 | "cell_type": "code", 216 | "execution_count": null, 217 | "id": "e7f9417c", 218 | "metadata": {}, 219 | "outputs": [], 220 | "source": [] 221 | }, 222 | { 223 | "cell_type": "markdown", 224 | "id": "5f75e7a8", 225 | "metadata": {}, 226 | "source": [ 227 | "#### 12. Create a 3x3x3 array with random values (★☆☆)" 228 | ] 229 | }, 230 | { 231 | "cell_type": "code", 232 | "execution_count": null, 233 | "id": "ec3c59bb", 234 | "metadata": {}, 235 | "outputs": [], 236 | "source": [] 237 | }, 238 | { 239 | "cell_type": "markdown", 240 | "id": "7f012f49", 241 | "metadata": {}, 242 | "source": [ 243 | "#### 13. Create a 10x10 array with random values and find the minimum and maximum values (★☆☆)" 244 | ] 245 | }, 246 | { 247 | "cell_type": "code", 248 | "execution_count": null, 249 | "id": "8247cae0", 250 | "metadata": {}, 251 | "outputs": [], 252 | "source": [] 253 | }, 254 | { 255 | "cell_type": "markdown", 256 | "id": "7d976fd0", 257 | "metadata": {}, 258 | "source": [ 259 | "#### 14. Create a random vector of size 30 and find the mean value (★☆☆)" 260 | ] 261 | }, 262 | { 263 | "cell_type": "code", 264 | "execution_count": null, 265 | "id": "1d5c77fd", 266 | "metadata": {}, 267 | "outputs": [], 268 | "source": [] 269 | }, 270 | { 271 | "cell_type": "markdown", 272 | "id": "c5266946", 273 | "metadata": {}, 274 | "source": [ 275 | "#### 15. Create a 2d array with 1 on the border and 0 inside (★☆☆)" 276 | ] 277 | }, 278 | { 279 | "cell_type": "code", 280 | "execution_count": null, 281 | "id": "140eff80", 282 | "metadata": {}, 283 | "outputs": [], 284 | "source": [] 285 | }, 286 | { 287 | "cell_type": "markdown", 288 | "id": "2dd11b32", 289 | "metadata": {}, 290 | "source": [ 291 | "#### 16. How to add a border (filled with 0's) around an existing array? (★☆☆)" 292 | ] 293 | }, 294 | { 295 | "cell_type": "code", 296 | "execution_count": null, 297 | "id": "ab1d50a8", 298 | "metadata": {}, 299 | "outputs": [], 300 | "source": [] 301 | }, 302 | { 303 | "cell_type": "markdown", 304 | "id": "a7c39246", 305 | "metadata": {}, 306 | "source": [ 307 | "#### 17. What is the result of the following expression? (★☆☆)\n", 308 | "```python\n", 309 | "0 * np.nan\n", 310 | "np.nan == np.nan\n", 311 | "np.inf > np.nan\n", 312 | "np.nan - np.nan\n", 313 | "np.nan in set([np.nan])\n", 314 | "0.3 == 3 * 0.1\n", 315 | "```" 316 | ] 317 | }, 318 | { 319 | "cell_type": "code", 320 | "execution_count": null, 321 | "id": "d5f154f3", 322 | "metadata": {}, 323 | "outputs": [], 324 | "source": [] 325 | }, 326 | { 327 | "cell_type": "markdown", 328 | "id": "757aff7a", 329 | "metadata": {}, 330 | "source": [ 331 | "#### 18. Create a 5x5 matrix with values 1,2,3,4 just below the diagonal (★☆☆)" 332 | ] 333 | }, 334 | { 335 | "cell_type": "code", 336 | "execution_count": null, 337 | "id": "fc9309c9", 338 | "metadata": {}, 339 | "outputs": [], 340 | "source": [] 341 | }, 342 | { 343 | "cell_type": "markdown", 344 | "id": "ae259b07", 345 | "metadata": {}, 346 | "source": [ 347 | "#### 19. Create a 8x8 matrix and fill it with a checkerboard pattern (★☆☆)" 348 | ] 349 | }, 350 | { 351 | "cell_type": "code", 352 | "execution_count": null, 353 | "id": "ceccc277", 354 | "metadata": {}, 355 | "outputs": [], 356 | "source": [] 357 | }, 358 | { 359 | "cell_type": "markdown", 360 | "id": "9f5d548e", 361 | "metadata": {}, 362 | "source": [ 363 | "#### 20. Consider a (6,7,8) shape array, what is the index (x,y,z) of the 100th element? (★☆☆)" 364 | ] 365 | }, 366 | { 367 | "cell_type": "code", 368 | "execution_count": null, 369 | "id": "ebf6fa3c", 370 | "metadata": {}, 371 | "outputs": [], 372 | "source": [] 373 | }, 374 | { 375 | "cell_type": "markdown", 376 | "id": "e1fe826b", 377 | "metadata": {}, 378 | "source": [ 379 | "#### 21. Create a checkerboard 8x8 matrix using the tile function (★☆☆)" 380 | ] 381 | }, 382 | { 383 | "cell_type": "code", 384 | "execution_count": null, 385 | "id": "7cbd262a", 386 | "metadata": {}, 387 | "outputs": [], 388 | "source": [] 389 | }, 390 | { 391 | "cell_type": "markdown", 392 | "id": "3cc99a9e", 393 | "metadata": {}, 394 | "source": [ 395 | "#### 22. Normalize a 5x5 random matrix (★☆☆)" 396 | ] 397 | }, 398 | { 399 | "cell_type": "code", 400 | "execution_count": null, 401 | "id": "96ec3796", 402 | "metadata": {}, 403 | "outputs": [], 404 | "source": [] 405 | }, 406 | { 407 | "cell_type": "markdown", 408 | "id": "3cefb279", 409 | "metadata": {}, 410 | "source": [ 411 | "#### 23. Create a custom dtype that describes a color as four unsigned bytes (RGBA) (★☆☆)" 412 | ] 413 | }, 414 | { 415 | "cell_type": "code", 416 | "execution_count": null, 417 | "id": "06231cc7", 418 | "metadata": {}, 419 | "outputs": [], 420 | "source": [] 421 | }, 422 | { 423 | "cell_type": "markdown", 424 | "id": "04177bf2", 425 | "metadata": {}, 426 | "source": [ 427 | "#### 24. Multiply a 5x3 matrix by a 3x2 matrix (real matrix product) (★☆☆)" 428 | ] 429 | }, 430 | { 431 | "cell_type": "code", 432 | "execution_count": null, 433 | "id": "25c78847", 434 | "metadata": {}, 435 | "outputs": [], 436 | "source": [] 437 | }, 438 | { 439 | "cell_type": "markdown", 440 | "id": "14a38540", 441 | "metadata": {}, 442 | "source": [ 443 | "#### 25. Given a 1D array, negate all elements which are between 3 and 8, in place. (★☆☆)" 444 | ] 445 | }, 446 | { 447 | "cell_type": "code", 448 | "execution_count": null, 449 | "id": "85a57a73", 450 | "metadata": {}, 451 | "outputs": [], 452 | "source": [] 453 | }, 454 | { 455 | "cell_type": "markdown", 456 | "id": "bb586fda", 457 | "metadata": {}, 458 | "source": [ 459 | "#### 26. What is the output of the following script? (★☆☆)\n", 460 | "```python\n", 461 | "# Author: Jake VanderPlas\n", 462 | "\n", 463 | "print(sum(range(5),-1))\n", 464 | "from numpy import *\n", 465 | "print(sum(range(5),-1))\n", 466 | "```" 467 | ] 468 | }, 469 | { 470 | "cell_type": "code", 471 | "execution_count": null, 472 | "id": "5094a699", 473 | "metadata": {}, 474 | "outputs": [], 475 | "source": [] 476 | }, 477 | { 478 | "cell_type": "markdown", 479 | "id": "198cdc05", 480 | "metadata": {}, 481 | "source": [ 482 | "#### 27. Consider an integer vector Z, which of these expressions are legal? (★☆☆)\n", 483 | "```python\n", 484 | "Z**Z\n", 485 | "2 << Z >> 2\n", 486 | "Z <- Z\n", 487 | "1j*Z\n", 488 | "Z/1/1\n", 489 | "ZZ\n", 490 | "```" 491 | ] 492 | }, 493 | { 494 | "cell_type": "code", 495 | "execution_count": null, 496 | "id": "a4195583", 497 | "metadata": {}, 498 | "outputs": [], 499 | "source": [] 500 | }, 501 | { 502 | "cell_type": "markdown", 503 | "id": "d83bb54b", 504 | "metadata": {}, 505 | "source": [ 506 | "#### 28. What are the result of the following expressions? (★☆☆)\n", 507 | "```python\n", 508 | "np.array(0) / np.array(0)\n", 509 | "np.array(0) // np.array(0)\n", 510 | "np.array([np.nan]).astype(int).astype(float)\n", 511 | "```" 512 | ] 513 | }, 514 | { 515 | "cell_type": "code", 516 | "execution_count": null, 517 | "id": "277bd109", 518 | "metadata": {}, 519 | "outputs": [], 520 | "source": [] 521 | }, 522 | { 523 | "cell_type": "markdown", 524 | "id": "415d2d18", 525 | "metadata": {}, 526 | "source": [ 527 | "#### 29. How to round away from zero a float array ? (★☆☆)" 528 | ] 529 | }, 530 | { 531 | "cell_type": "code", 532 | "execution_count": null, 533 | "id": "63df40b7", 534 | "metadata": {}, 535 | "outputs": [], 536 | "source": [] 537 | }, 538 | { 539 | "cell_type": "markdown", 540 | "id": "40ddc32c", 541 | "metadata": {}, 542 | "source": [ 543 | "#### 30. How to find common values between two arrays? (★☆☆)" 544 | ] 545 | }, 546 | { 547 | "cell_type": "code", 548 | "execution_count": null, 549 | "id": "e4e221c3", 550 | "metadata": {}, 551 | "outputs": [], 552 | "source": [] 553 | }, 554 | { 555 | "cell_type": "markdown", 556 | "id": "96a2b00a", 557 | "metadata": {}, 558 | "source": [ 559 | "#### 31. How to ignore all numpy warnings (not recommended)? (★☆☆)" 560 | ] 561 | }, 562 | { 563 | "cell_type": "code", 564 | "execution_count": null, 565 | "id": "97517a73", 566 | "metadata": {}, 567 | "outputs": [], 568 | "source": [] 569 | }, 570 | { 571 | "cell_type": "markdown", 572 | "id": "5164e541", 573 | "metadata": {}, 574 | "source": [ 575 | "#### 32. Is the following expressions true? (★☆☆)\n", 576 | "```python\n", 577 | "np.sqrt(-1) == np.emath.sqrt(-1)\n", 578 | "```" 579 | ] 580 | }, 581 | { 582 | "cell_type": "code", 583 | "execution_count": null, 584 | "id": "c05aab40", 585 | "metadata": {}, 586 | "outputs": [], 587 | "source": [] 588 | }, 589 | { 590 | "cell_type": "markdown", 591 | "id": "6ff7fdf8", 592 | "metadata": {}, 593 | "source": [ 594 | "#### 33. How to get the dates of yesterday, today and tomorrow? (★☆☆)" 595 | ] 596 | }, 597 | { 598 | "cell_type": "code", 599 | "execution_count": null, 600 | "id": "6156213d", 601 | "metadata": {}, 602 | "outputs": [], 603 | "source": [] 604 | }, 605 | { 606 | "cell_type": "markdown", 607 | "id": "97dde2a7", 608 | "metadata": {}, 609 | "source": [ 610 | "#### 34. How to get all the dates corresponding to the month of July 2016? (★★☆)" 611 | ] 612 | }, 613 | { 614 | "cell_type": "code", 615 | "execution_count": null, 616 | "id": "249806a3", 617 | "metadata": {}, 618 | "outputs": [], 619 | "source": [] 620 | }, 621 | { 622 | "cell_type": "markdown", 623 | "id": "78f4ad65", 624 | "metadata": {}, 625 | "source": [ 626 | "#### 35. How to compute ((A+B)*(-A/2)) in place (without copy)? (★★☆)" 627 | ] 628 | }, 629 | { 630 | "cell_type": "code", 631 | "execution_count": null, 632 | "id": "d9bee25c", 633 | "metadata": {}, 634 | "outputs": [], 635 | "source": [] 636 | }, 637 | { 638 | "cell_type": "markdown", 639 | "id": "1a194d91", 640 | "metadata": {}, 641 | "source": [ 642 | "#### 36. Extract the integer part of a random array of positive numbers using 4 different methods (★★☆)" 643 | ] 644 | }, 645 | { 646 | "cell_type": "code", 647 | "execution_count": null, 648 | "id": "46a4ab0a", 649 | "metadata": {}, 650 | "outputs": [], 651 | "source": [] 652 | }, 653 | { 654 | "cell_type": "markdown", 655 | "id": "23a9130d", 656 | "metadata": {}, 657 | "source": [ 658 | "#### 37. Create a 5x5 matrix with row values ranging from 0 to 4 (★★☆)" 659 | ] 660 | }, 661 | { 662 | "cell_type": "code", 663 | "execution_count": null, 664 | "id": "8a08a042", 665 | "metadata": {}, 666 | "outputs": [], 667 | "source": [] 668 | }, 669 | { 670 | "cell_type": "markdown", 671 | "id": "e225eafa", 672 | "metadata": {}, 673 | "source": [ 674 | "#### 38. Consider a generator function that generates 10 integers and use it to build an array (★☆☆)" 675 | ] 676 | }, 677 | { 678 | "cell_type": "code", 679 | "execution_count": null, 680 | "id": "7c2acc82", 681 | "metadata": {}, 682 | "outputs": [], 683 | "source": [] 684 | }, 685 | { 686 | "cell_type": "markdown", 687 | "id": "2f61a8f5", 688 | "metadata": {}, 689 | "source": [ 690 | "#### 39. Create a vector of size 10 with values ranging from 0 to 1, both excluded (★★☆)" 691 | ] 692 | }, 693 | { 694 | "cell_type": "code", 695 | "execution_count": null, 696 | "id": "ef7bc11c", 697 | "metadata": {}, 698 | "outputs": [], 699 | "source": [] 700 | }, 701 | { 702 | "cell_type": "markdown", 703 | "id": "d5ae0694", 704 | "metadata": {}, 705 | "source": [ 706 | "#### 40. Create a random vector of size 10 and sort it (★★☆)" 707 | ] 708 | }, 709 | { 710 | "cell_type": "code", 711 | "execution_count": null, 712 | "id": "0b5a407d", 713 | "metadata": {}, 714 | "outputs": [], 715 | "source": [] 716 | }, 717 | { 718 | "cell_type": "markdown", 719 | "id": "1a355962", 720 | "metadata": {}, 721 | "source": [ 722 | "#### 41. How to sum a small array faster than np.sum? (★★☆)" 723 | ] 724 | }, 725 | { 726 | "cell_type": "code", 727 | "execution_count": null, 728 | "id": "70917f47", 729 | "metadata": {}, 730 | "outputs": [], 731 | "source": [] 732 | }, 733 | { 734 | "cell_type": "markdown", 735 | "id": "42e65d4e", 736 | "metadata": {}, 737 | "source": [ 738 | "#### 42. Consider two random arrays A and B, check if they are equal (★★☆)" 739 | ] 740 | }, 741 | { 742 | "cell_type": "code", 743 | "execution_count": null, 744 | "id": "c4ae0c00", 745 | "metadata": {}, 746 | "outputs": [], 747 | "source": [] 748 | }, 749 | { 750 | "cell_type": "markdown", 751 | "id": "37c295dd", 752 | "metadata": {}, 753 | "source": [ 754 | "#### 43. Make an array immutable (read-only) (★★☆)" 755 | ] 756 | }, 757 | { 758 | "cell_type": "code", 759 | "execution_count": null, 760 | "id": "5a2cf158", 761 | "metadata": {}, 762 | "outputs": [], 763 | "source": [] 764 | }, 765 | { 766 | "cell_type": "markdown", 767 | "id": "e92096de", 768 | "metadata": {}, 769 | "source": [ 770 | "#### 44. Consider a random 10x2 matrix representing cartesian coordinates, convert them to polar coordinates (★★☆)" 771 | ] 772 | }, 773 | { 774 | "cell_type": "code", 775 | "execution_count": null, 776 | "id": "7d4f2602", 777 | "metadata": {}, 778 | "outputs": [], 779 | "source": [] 780 | }, 781 | { 782 | "cell_type": "markdown", 783 | "id": "a71d88ea", 784 | "metadata": {}, 785 | "source": [ 786 | "#### 45. Create random vector of size 10 and replace the maximum value by 0 (★★☆)" 787 | ] 788 | }, 789 | { 790 | "cell_type": "code", 791 | "execution_count": null, 792 | "id": "1298225a", 793 | "metadata": {}, 794 | "outputs": [], 795 | "source": [] 796 | }, 797 | { 798 | "cell_type": "markdown", 799 | "id": "261c253c", 800 | "metadata": {}, 801 | "source": [ 802 | "#### 46. Create a structured array with `x` and `y` coordinates covering the [0,1]x[0,1] area (★★☆)" 803 | ] 804 | }, 805 | { 806 | "cell_type": "code", 807 | "execution_count": null, 808 | "id": "9150a4a1", 809 | "metadata": {}, 810 | "outputs": [], 811 | "source": [] 812 | }, 813 | { 814 | "cell_type": "markdown", 815 | "id": "265deebd", 816 | "metadata": {}, 817 | "source": [ 818 | "#### 47. Given two arrays, X and Y, construct the Cauchy matrix C (Cij =1/(xi - yj)) (★★☆)" 819 | ] 820 | }, 821 | { 822 | "cell_type": "code", 823 | "execution_count": null, 824 | "id": "9fad2a0d", 825 | "metadata": {}, 826 | "outputs": [], 827 | "source": [] 828 | }, 829 | { 830 | "cell_type": "markdown", 831 | "id": "f9007f53", 832 | "metadata": {}, 833 | "source": [ 834 | "#### 48. Print the minimum and maximum representable values for each numpy scalar type (★★☆)" 835 | ] 836 | }, 837 | { 838 | "cell_type": "code", 839 | "execution_count": null, 840 | "id": "2a97c51a", 841 | "metadata": {}, 842 | "outputs": [], 843 | "source": [] 844 | }, 845 | { 846 | "cell_type": "markdown", 847 | "id": "5130ea82", 848 | "metadata": {}, 849 | "source": [ 850 | "#### 49. How to print all the values of an array? (★★☆)" 851 | ] 852 | }, 853 | { 854 | "cell_type": "code", 855 | "execution_count": null, 856 | "id": "4636aa7a", 857 | "metadata": {}, 858 | "outputs": [], 859 | "source": [] 860 | }, 861 | { 862 | "cell_type": "markdown", 863 | "id": "56edae30", 864 | "metadata": {}, 865 | "source": [ 866 | "#### 50. How to find the closest value (to a given scalar) in a vector? (★★☆)" 867 | ] 868 | }, 869 | { 870 | "cell_type": "code", 871 | "execution_count": null, 872 | "id": "b34f3cf0", 873 | "metadata": {}, 874 | "outputs": [], 875 | "source": [] 876 | }, 877 | { 878 | "cell_type": "markdown", 879 | "id": "a8f3578d", 880 | "metadata": {}, 881 | "source": [ 882 | "#### 51. Create a structured array representing a position (x,y) and a color (r,g,b) (★★☆)" 883 | ] 884 | }, 885 | { 886 | "cell_type": "code", 887 | "execution_count": null, 888 | "id": "4e9c2e30", 889 | "metadata": {}, 890 | "outputs": [], 891 | "source": [] 892 | }, 893 | { 894 | "cell_type": "markdown", 895 | "id": "cd41c4dc", 896 | "metadata": {}, 897 | "source": [ 898 | "#### 52. Consider a random vector with shape (100,2) representing coordinates, find point by point distances (★★☆)" 899 | ] 900 | }, 901 | { 902 | "cell_type": "code", 903 | "execution_count": null, 904 | "id": "53f15c5d", 905 | "metadata": {}, 906 | "outputs": [], 907 | "source": [] 908 | }, 909 | { 910 | "cell_type": "markdown", 911 | "id": "0e2990a0", 912 | "metadata": {}, 913 | "source": [ 914 | "#### 53. How to convert a float (32 bits) array into an integer (32 bits) array in place?" 915 | ] 916 | }, 917 | { 918 | "cell_type": "code", 919 | "execution_count": null, 920 | "id": "8d7e441e", 921 | "metadata": {}, 922 | "outputs": [], 923 | "source": [] 924 | }, 925 | { 926 | "cell_type": "markdown", 927 | "id": "9e3fae09", 928 | "metadata": {}, 929 | "source": [ 930 | "#### 54. How to read the following file? (★★☆)\n", 931 | "```\n", 932 | "1, 2, 3, 4, 5\n", 933 | "6, , , 7, 8\n", 934 | " , , 9,10,11\n", 935 | "```" 936 | ] 937 | }, 938 | { 939 | "cell_type": "code", 940 | "execution_count": null, 941 | "id": "5ce8d677", 942 | "metadata": {}, 943 | "outputs": [], 944 | "source": [] 945 | }, 946 | { 947 | "cell_type": "markdown", 948 | "id": "dc8e013a", 949 | "metadata": {}, 950 | "source": [ 951 | "#### 55. What is the equivalent of enumerate for numpy arrays? (★★☆)" 952 | ] 953 | }, 954 | { 955 | "cell_type": "code", 956 | "execution_count": null, 957 | "id": "6b46c440", 958 | "metadata": {}, 959 | "outputs": [], 960 | "source": [] 961 | }, 962 | { 963 | "cell_type": "markdown", 964 | "id": "acdcd8d9", 965 | "metadata": {}, 966 | "source": [ 967 | "#### 56. Generate a generic 2D Gaussian-like array (★★☆)" 968 | ] 969 | }, 970 | { 971 | "cell_type": "code", 972 | "execution_count": null, 973 | "id": "c00f8b49", 974 | "metadata": {}, 975 | "outputs": [], 976 | "source": [] 977 | }, 978 | { 979 | "cell_type": "markdown", 980 | "id": "3f0bf645", 981 | "metadata": {}, 982 | "source": [ 983 | "#### 57. How to randomly place p elements in a 2D array? (★★☆)" 984 | ] 985 | }, 986 | { 987 | "cell_type": "code", 988 | "execution_count": null, 989 | "id": "bac7ed71", 990 | "metadata": {}, 991 | "outputs": [], 992 | "source": [] 993 | }, 994 | { 995 | "cell_type": "markdown", 996 | "id": "b9ac42fc", 997 | "metadata": {}, 998 | "source": [ 999 | "#### 58. Subtract the mean of each row of a matrix (★★☆)" 1000 | ] 1001 | }, 1002 | { 1003 | "cell_type": "code", 1004 | "execution_count": null, 1005 | "id": "0cac0138", 1006 | "metadata": {}, 1007 | "outputs": [], 1008 | "source": [] 1009 | }, 1010 | { 1011 | "cell_type": "markdown", 1012 | "id": "f2c2e314", 1013 | "metadata": {}, 1014 | "source": [ 1015 | "#### 59. How to sort an array by the nth column? (★★☆)" 1016 | ] 1017 | }, 1018 | { 1019 | "cell_type": "code", 1020 | "execution_count": null, 1021 | "id": "61739197", 1022 | "metadata": {}, 1023 | "outputs": [], 1024 | "source": [] 1025 | }, 1026 | { 1027 | "cell_type": "markdown", 1028 | "id": "e8311ecb", 1029 | "metadata": {}, 1030 | "source": [ 1031 | "#### 60. How to tell if a given 2D array has null columns? (★★☆)" 1032 | ] 1033 | }, 1034 | { 1035 | "cell_type": "code", 1036 | "execution_count": null, 1037 | "id": "a3fd8a79", 1038 | "metadata": {}, 1039 | "outputs": [], 1040 | "source": [] 1041 | }, 1042 | { 1043 | "cell_type": "markdown", 1044 | "id": "e9617f44", 1045 | "metadata": {}, 1046 | "source": [ 1047 | "#### 61. Find the nearest value from a given value in an array (★★☆)" 1048 | ] 1049 | }, 1050 | { 1051 | "cell_type": "code", 1052 | "execution_count": null, 1053 | "id": "2fb40d45", 1054 | "metadata": {}, 1055 | "outputs": [], 1056 | "source": [] 1057 | }, 1058 | { 1059 | "cell_type": "markdown", 1060 | "id": "892813ba", 1061 | "metadata": {}, 1062 | "source": [ 1063 | "#### 62. Considering two arrays with shape (1,3) and (3,1), how to compute their sum using an iterator? (★★☆)" 1064 | ] 1065 | }, 1066 | { 1067 | "cell_type": "code", 1068 | "execution_count": null, 1069 | "id": "0ec3c1ee", 1070 | "metadata": {}, 1071 | "outputs": [], 1072 | "source": [] 1073 | }, 1074 | { 1075 | "cell_type": "markdown", 1076 | "id": "467ff234", 1077 | "metadata": {}, 1078 | "source": [ 1079 | "#### 63. Create an array class that has a name attribute (★★☆)" 1080 | ] 1081 | }, 1082 | { 1083 | "cell_type": "code", 1084 | "execution_count": null, 1085 | "id": "43d6ba35", 1086 | "metadata": {}, 1087 | "outputs": [], 1088 | "source": [] 1089 | }, 1090 | { 1091 | "cell_type": "markdown", 1092 | "id": "af15b01a", 1093 | "metadata": {}, 1094 | "source": [ 1095 | "#### 64. Consider a given vector, how to add 1 to each element indexed by a second vector (be careful with repeated indices)? (★★★)" 1096 | ] 1097 | }, 1098 | { 1099 | "cell_type": "code", 1100 | "execution_count": null, 1101 | "id": "52d9315d", 1102 | "metadata": {}, 1103 | "outputs": [], 1104 | "source": [] 1105 | }, 1106 | { 1107 | "cell_type": "markdown", 1108 | "id": "62d21ba4", 1109 | "metadata": {}, 1110 | "source": [ 1111 | "#### 65. How to accumulate elements of a vector (X) to an array (F) based on an index list (I)? (★★★)" 1112 | ] 1113 | }, 1114 | { 1115 | "cell_type": "code", 1116 | "execution_count": null, 1117 | "id": "56497ebc", 1118 | "metadata": {}, 1119 | "outputs": [], 1120 | "source": [] 1121 | }, 1122 | { 1123 | "cell_type": "markdown", 1124 | "id": "fd7e0104", 1125 | "metadata": {}, 1126 | "source": [ 1127 | "#### 66. Considering a (w,h,3) image of (dtype=ubyte), compute the number of unique colors (★★☆)" 1128 | ] 1129 | }, 1130 | { 1131 | "cell_type": "code", 1132 | "execution_count": null, 1133 | "id": "1cf3edec", 1134 | "metadata": {}, 1135 | "outputs": [], 1136 | "source": [] 1137 | }, 1138 | { 1139 | "cell_type": "markdown", 1140 | "id": "dd70e081", 1141 | "metadata": {}, 1142 | "source": [ 1143 | "#### 67. Considering a four dimensions array, how to get sum over the last two axis at once? (★★★)" 1144 | ] 1145 | }, 1146 | { 1147 | "cell_type": "code", 1148 | "execution_count": null, 1149 | "id": "e36af36e", 1150 | "metadata": {}, 1151 | "outputs": [], 1152 | "source": [] 1153 | }, 1154 | { 1155 | "cell_type": "markdown", 1156 | "id": "58333fa3", 1157 | "metadata": {}, 1158 | "source": [ 1159 | "#### 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? (★★★)" 1160 | ] 1161 | }, 1162 | { 1163 | "cell_type": "code", 1164 | "execution_count": null, 1165 | "id": "acfc823e", 1166 | "metadata": {}, 1167 | "outputs": [], 1168 | "source": [] 1169 | }, 1170 | { 1171 | "cell_type": "markdown", 1172 | "id": "afbf2ff8", 1173 | "metadata": {}, 1174 | "source": [ 1175 | "#### 69. How to get the diagonal of a dot product? (★★★)" 1176 | ] 1177 | }, 1178 | { 1179 | "cell_type": "code", 1180 | "execution_count": null, 1181 | "id": "8b44d9cb", 1182 | "metadata": {}, 1183 | "outputs": [], 1184 | "source": [] 1185 | }, 1186 | { 1187 | "cell_type": "markdown", 1188 | "id": "01a1aeea", 1189 | "metadata": {}, 1190 | "source": [ 1191 | "#### 70. Consider the vector [1, 2, 3, 4, 5], how to build a new vector with 3 consecutive zeros interleaved between each value? (★★★)" 1192 | ] 1193 | }, 1194 | { 1195 | "cell_type": "code", 1196 | "execution_count": null, 1197 | "id": "2105434f", 1198 | "metadata": {}, 1199 | "outputs": [], 1200 | "source": [] 1201 | }, 1202 | { 1203 | "cell_type": "markdown", 1204 | "id": "1da61b2c", 1205 | "metadata": {}, 1206 | "source": [ 1207 | "#### 71. Consider an array of dimension (5,5,3), how to multiply it by an array with dimensions (5,5)? (★★★)" 1208 | ] 1209 | }, 1210 | { 1211 | "cell_type": "code", 1212 | "execution_count": null, 1213 | "id": "0f257760", 1214 | "metadata": {}, 1215 | "outputs": [], 1216 | "source": [] 1217 | }, 1218 | { 1219 | "cell_type": "markdown", 1220 | "id": "d465a23a", 1221 | "metadata": {}, 1222 | "source": [ 1223 | "#### 72. How to swap two rows of an array? (★★★)" 1224 | ] 1225 | }, 1226 | { 1227 | "cell_type": "code", 1228 | "execution_count": null, 1229 | "id": "85dbac4a", 1230 | "metadata": {}, 1231 | "outputs": [], 1232 | "source": [] 1233 | }, 1234 | { 1235 | "cell_type": "markdown", 1236 | "id": "64916675", 1237 | "metadata": {}, 1238 | "source": [ 1239 | "#### 73. Consider a set of 10 triplets describing 10 triangles (with shared vertices), find the set of unique line segments composing all the triangles (★★★)" 1240 | ] 1241 | }, 1242 | { 1243 | "cell_type": "code", 1244 | "execution_count": null, 1245 | "id": "22cf4ff6", 1246 | "metadata": {}, 1247 | "outputs": [], 1248 | "source": [] 1249 | }, 1250 | { 1251 | "cell_type": "markdown", 1252 | "id": "5ac69993", 1253 | "metadata": {}, 1254 | "source": [ 1255 | "#### 74. Given a sorted array C that corresponds to a bincount, how to produce an array A such that np.bincount(A) == C? (★★★)" 1256 | ] 1257 | }, 1258 | { 1259 | "cell_type": "code", 1260 | "execution_count": null, 1261 | "id": "6e2b4a3b", 1262 | "metadata": {}, 1263 | "outputs": [], 1264 | "source": [] 1265 | }, 1266 | { 1267 | "cell_type": "markdown", 1268 | "id": "41ae2500", 1269 | "metadata": {}, 1270 | "source": [ 1271 | "#### 75. How to compute averages using a sliding window over an array? (★★★)" 1272 | ] 1273 | }, 1274 | { 1275 | "cell_type": "code", 1276 | "execution_count": null, 1277 | "id": "460cdb46", 1278 | "metadata": {}, 1279 | "outputs": [], 1280 | "source": [] 1281 | }, 1282 | { 1283 | "cell_type": "markdown", 1284 | "id": "8a968a39", 1285 | "metadata": {}, 1286 | "source": [ 1287 | "#### 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]) (★★★)" 1288 | ] 1289 | }, 1290 | { 1291 | "cell_type": "code", 1292 | "execution_count": null, 1293 | "id": "5d37d9b3", 1294 | "metadata": {}, 1295 | "outputs": [], 1296 | "source": [] 1297 | }, 1298 | { 1299 | "cell_type": "markdown", 1300 | "id": "d8c056da", 1301 | "metadata": {}, 1302 | "source": [ 1303 | "#### 77. How to negate a boolean, or to change the sign of a float inplace? (★★★)" 1304 | ] 1305 | }, 1306 | { 1307 | "cell_type": "code", 1308 | "execution_count": null, 1309 | "id": "3a0ba740", 1310 | "metadata": {}, 1311 | "outputs": [], 1312 | "source": [] 1313 | }, 1314 | { 1315 | "cell_type": "markdown", 1316 | "id": "6a2632c8", 1317 | "metadata": {}, 1318 | "source": [ 1319 | "#### 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])? (★★★)" 1320 | ] 1321 | }, 1322 | { 1323 | "cell_type": "code", 1324 | "execution_count": null, 1325 | "id": "cce12b75", 1326 | "metadata": {}, 1327 | "outputs": [], 1328 | "source": [] 1329 | }, 1330 | { 1331 | "cell_type": "markdown", 1332 | "id": "7cba6ae9", 1333 | "metadata": {}, 1334 | "source": [ 1335 | "#### 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])? (★★★)" 1336 | ] 1337 | }, 1338 | { 1339 | "cell_type": "code", 1340 | "execution_count": null, 1341 | "id": "576c542d", 1342 | "metadata": {}, 1343 | "outputs": [], 1344 | "source": [] 1345 | }, 1346 | { 1347 | "cell_type": "markdown", 1348 | "id": "1402e9db", 1349 | "metadata": {}, 1350 | "source": [ 1351 | "#### 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) (★★★)" 1352 | ] 1353 | }, 1354 | { 1355 | "cell_type": "code", 1356 | "execution_count": null, 1357 | "id": "8aa89c72", 1358 | "metadata": {}, 1359 | "outputs": [], 1360 | "source": [] 1361 | }, 1362 | { 1363 | "cell_type": "markdown", 1364 | "id": "159a6dff", 1365 | "metadata": {}, 1366 | "source": [ 1367 | "#### 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]]? (★★★)" 1368 | ] 1369 | }, 1370 | { 1371 | "cell_type": "code", 1372 | "execution_count": null, 1373 | "id": "ce160b57", 1374 | "metadata": {}, 1375 | "outputs": [], 1376 | "source": [] 1377 | }, 1378 | { 1379 | "cell_type": "markdown", 1380 | "id": "9479f684", 1381 | "metadata": {}, 1382 | "source": [ 1383 | "#### 82. Compute a matrix rank (★★★)" 1384 | ] 1385 | }, 1386 | { 1387 | "cell_type": "code", 1388 | "execution_count": null, 1389 | "id": "9a6e088c", 1390 | "metadata": {}, 1391 | "outputs": [], 1392 | "source": [] 1393 | }, 1394 | { 1395 | "cell_type": "markdown", 1396 | "id": "5b6a81c5", 1397 | "metadata": {}, 1398 | "source": [ 1399 | "#### 83. How to find the most frequent value in an array?" 1400 | ] 1401 | }, 1402 | { 1403 | "cell_type": "code", 1404 | "execution_count": null, 1405 | "id": "cf1864ba", 1406 | "metadata": {}, 1407 | "outputs": [], 1408 | "source": [] 1409 | }, 1410 | { 1411 | "cell_type": "markdown", 1412 | "id": "8142c362", 1413 | "metadata": {}, 1414 | "source": [ 1415 | "#### 84. Extract all the contiguous 3x3 blocks from a random 10x10 matrix (★★★)" 1416 | ] 1417 | }, 1418 | { 1419 | "cell_type": "code", 1420 | "execution_count": null, 1421 | "id": "18b475ed", 1422 | "metadata": {}, 1423 | "outputs": [], 1424 | "source": [] 1425 | }, 1426 | { 1427 | "cell_type": "markdown", 1428 | "id": "6870a477", 1429 | "metadata": {}, 1430 | "source": [ 1431 | "#### 85. Create a 2D array subclass such that Z[i,j] == Z[j,i] (★★★)" 1432 | ] 1433 | }, 1434 | { 1435 | "cell_type": "code", 1436 | "execution_count": null, 1437 | "id": "13de2582", 1438 | "metadata": {}, 1439 | "outputs": [], 1440 | "source": [] 1441 | }, 1442 | { 1443 | "cell_type": "markdown", 1444 | "id": "502a6bb6", 1445 | "metadata": {}, 1446 | "source": [ 1447 | "#### 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)) (★★★)" 1448 | ] 1449 | }, 1450 | { 1451 | "cell_type": "code", 1452 | "execution_count": null, 1453 | "id": "5f575c8e", 1454 | "metadata": {}, 1455 | "outputs": [], 1456 | "source": [] 1457 | }, 1458 | { 1459 | "cell_type": "markdown", 1460 | "id": "b974e01e", 1461 | "metadata": {}, 1462 | "source": [ 1463 | "#### 87. Consider a 16x16 array, how to get the block-sum (block size is 4x4)? (★★★)" 1464 | ] 1465 | }, 1466 | { 1467 | "cell_type": "code", 1468 | "execution_count": null, 1469 | "id": "6e691289", 1470 | "metadata": {}, 1471 | "outputs": [], 1472 | "source": [] 1473 | }, 1474 | { 1475 | "cell_type": "markdown", 1476 | "id": "0b8c10c7", 1477 | "metadata": {}, 1478 | "source": [ 1479 | "#### 88. How to implement the Game of Life using numpy arrays? (★★★)" 1480 | ] 1481 | }, 1482 | { 1483 | "cell_type": "code", 1484 | "execution_count": null, 1485 | "id": "cd02f7f3", 1486 | "metadata": {}, 1487 | "outputs": [], 1488 | "source": [] 1489 | }, 1490 | { 1491 | "cell_type": "markdown", 1492 | "id": "e3f82541", 1493 | "metadata": {}, 1494 | "source": [ 1495 | "#### 89. How to get the n largest values of an array (★★★)" 1496 | ] 1497 | }, 1498 | { 1499 | "cell_type": "code", 1500 | "execution_count": null, 1501 | "id": "4fbd0146", 1502 | "metadata": {}, 1503 | "outputs": [], 1504 | "source": [] 1505 | }, 1506 | { 1507 | "cell_type": "markdown", 1508 | "id": "a7539391", 1509 | "metadata": {}, 1510 | "source": [ 1511 | "#### 90. Given an arbitrary number of vectors, build the cartesian product (every combination of every item) (★★★)" 1512 | ] 1513 | }, 1514 | { 1515 | "cell_type": "code", 1516 | "execution_count": null, 1517 | "id": "c6981e30", 1518 | "metadata": {}, 1519 | "outputs": [], 1520 | "source": [] 1521 | }, 1522 | { 1523 | "cell_type": "markdown", 1524 | "id": "faf28eb3", 1525 | "metadata": {}, 1526 | "source": [ 1527 | "#### 91. How to create a record array from a regular array? (★★★)" 1528 | ] 1529 | }, 1530 | { 1531 | "cell_type": "code", 1532 | "execution_count": null, 1533 | "id": "bf3c36e8", 1534 | "metadata": {}, 1535 | "outputs": [], 1536 | "source": [] 1537 | }, 1538 | { 1539 | "cell_type": "markdown", 1540 | "id": "bd45d52b", 1541 | "metadata": {}, 1542 | "source": [ 1543 | "#### 92. Consider a large vector Z, compute Z to the power of 3 using 3 different methods (★★★)" 1544 | ] 1545 | }, 1546 | { 1547 | "cell_type": "code", 1548 | "execution_count": null, 1549 | "id": "57add736", 1550 | "metadata": {}, 1551 | "outputs": [], 1552 | "source": [] 1553 | }, 1554 | { 1555 | "cell_type": "markdown", 1556 | "id": "6403bb1e", 1557 | "metadata": {}, 1558 | "source": [ 1559 | "#### 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? (★★★)" 1560 | ] 1561 | }, 1562 | { 1563 | "cell_type": "code", 1564 | "execution_count": null, 1565 | "id": "5e99e376", 1566 | "metadata": {}, 1567 | "outputs": [], 1568 | "source": [] 1569 | }, 1570 | { 1571 | "cell_type": "markdown", 1572 | "id": "2b1a4d2d", 1573 | "metadata": {}, 1574 | "source": [ 1575 | "#### 94. Considering a 10x3 matrix, extract rows with unequal values (e.g. [2,2,3]) (★★★)" 1576 | ] 1577 | }, 1578 | { 1579 | "cell_type": "code", 1580 | "execution_count": null, 1581 | "id": "9d12a8cd", 1582 | "metadata": {}, 1583 | "outputs": [], 1584 | "source": [] 1585 | }, 1586 | { 1587 | "cell_type": "markdown", 1588 | "id": "523fbb20", 1589 | "metadata": {}, 1590 | "source": [ 1591 | "#### 95. Convert a vector of ints into a matrix binary representation (★★★)" 1592 | ] 1593 | }, 1594 | { 1595 | "cell_type": "code", 1596 | "execution_count": null, 1597 | "id": "b17c2ce8", 1598 | "metadata": {}, 1599 | "outputs": [], 1600 | "source": [] 1601 | }, 1602 | { 1603 | "cell_type": "markdown", 1604 | "id": "3eb5ef69", 1605 | "metadata": {}, 1606 | "source": [ 1607 | "#### 96. Given a two dimensional array, how to extract unique rows? (★★★)" 1608 | ] 1609 | }, 1610 | { 1611 | "cell_type": "code", 1612 | "execution_count": null, 1613 | "id": "092c2c20", 1614 | "metadata": {}, 1615 | "outputs": [], 1616 | "source": [] 1617 | }, 1618 | { 1619 | "cell_type": "markdown", 1620 | "id": "c0e13fe1", 1621 | "metadata": {}, 1622 | "source": [ 1623 | "#### 97. Considering 2 vectors A & B, write the einsum equivalent of inner, outer, sum, and mul function (★★★)" 1624 | ] 1625 | }, 1626 | { 1627 | "cell_type": "code", 1628 | "execution_count": null, 1629 | "id": "b7b697cd", 1630 | "metadata": {}, 1631 | "outputs": [], 1632 | "source": [] 1633 | }, 1634 | { 1635 | "cell_type": "markdown", 1636 | "id": "cc071dbe", 1637 | "metadata": {}, 1638 | "source": [ 1639 | "#### 98. Considering a path described by two vectors (X,Y), how to sample it using equidistant samples (★★★)?" 1640 | ] 1641 | }, 1642 | { 1643 | "cell_type": "code", 1644 | "execution_count": null, 1645 | "id": "fec9fe86", 1646 | "metadata": {}, 1647 | "outputs": [], 1648 | "source": [] 1649 | }, 1650 | { 1651 | "cell_type": "markdown", 1652 | "id": "972f9dc3", 1653 | "metadata": {}, 1654 | "source": [ 1655 | "#### 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. (★★★)" 1656 | ] 1657 | }, 1658 | { 1659 | "cell_type": "code", 1660 | "execution_count": null, 1661 | "id": "5b284c86", 1662 | "metadata": {}, 1663 | "outputs": [], 1664 | "source": [] 1665 | }, 1666 | { 1667 | "cell_type": "markdown", 1668 | "id": "afad9d6e", 1669 | "metadata": {}, 1670 | "source": [ 1671 | "#### 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). (★★★)" 1672 | ] 1673 | }, 1674 | { 1675 | "cell_type": "code", 1676 | "execution_count": null, 1677 | "id": "f1885c64", 1678 | "metadata": {}, 1679 | "outputs": [], 1680 | "source": [] 1681 | } 1682 | ], 1683 | "metadata": {}, 1684 | "nbformat": 4, 1685 | "nbformat_minor": 5 1686 | } 1687 | -------------------------------------------------------------------------------- /100_Numpy_exercises.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | # 100 numpy exercises 5 | 6 | This is a collection of exercises that have been collected in the numpy mailing list, on stack overflow 7 | and in the numpy documentation. The goal of this collection is to offer a quick reference for both old 8 | and new users but also to provide a set of exercises for those who teach. 9 | 10 | 11 | If you find an error or think you've a better way to solve some of them, feel 12 | free to open an issue at . 13 | File automatically generated. See the documentation to update questions/answers/hints programmatically. 14 | 15 | #### 1. Import the numpy package under the name `np` (★☆☆) 16 | 17 | #### 2. Print the numpy version and the configuration (★☆☆) 18 | 19 | #### 3. Create a null vector of size 10 (★☆☆) 20 | 21 | #### 4. How to find the memory size of any array (★☆☆) 22 | 23 | #### 5. How to get the documentation of the numpy add function from the command line? (★☆☆) 24 | 25 | #### 6. Create a null vector of size 10 but the fifth value which is 1 (★☆☆) 26 | 27 | #### 7. Create a vector with values ranging from 10 to 49 (★☆☆) 28 | 29 | #### 8. Reverse a vector (first element becomes last) (★☆☆) 30 | 31 | #### 9. Create a 3x3 matrix with values ranging from 0 to 8 (★☆☆) 32 | 33 | #### 10. Find indices of non-zero elements from [1,2,0,0,4,0] (★☆☆) 34 | 35 | #### 11. Create a 3x3 identity matrix (★☆☆) 36 | 37 | #### 12. Create a 3x3x3 array with random values (★☆☆) 38 | 39 | #### 13. Create a 10x10 array with random values and find the minimum and maximum values (★☆☆) 40 | 41 | #### 14. Create a random vector of size 30 and find the mean value (★☆☆) 42 | 43 | #### 15. Create a 2d array with 1 on the border and 0 inside (★☆☆) 44 | 45 | #### 16. How to add a border (filled with 0's) around an existing array? (★☆☆) 46 | 47 | #### 17. What is the result of the following expression? (★☆☆) 48 | ```python 49 | 0 * np.nan 50 | np.nan == np.nan 51 | np.inf > np.nan 52 | np.nan - np.nan 53 | np.nan in set([np.nan]) 54 | 0.3 == 3 * 0.1 55 | ``` 56 | 57 | #### 18. Create a 5x5 matrix with values 1,2,3,4 just below the diagonal (★☆☆) 58 | 59 | #### 19. Create a 8x8 matrix and fill it with a checkerboard pattern (★☆☆) 60 | 61 | #### 20. Consider a (6,7,8) shape array, what is the index (x,y,z) of the 100th element? (★☆☆) 62 | 63 | #### 21. Create a checkerboard 8x8 matrix using the tile function (★☆☆) 64 | 65 | #### 22. Normalize a 5x5 random matrix (★☆☆) 66 | 67 | #### 23. Create a custom dtype that describes a color as four unsigned bytes (RGBA) (★☆☆) 68 | 69 | #### 24. Multiply a 5x3 matrix by a 3x2 matrix (real matrix product) (★☆☆) 70 | 71 | #### 25. Given a 1D array, negate all elements which are between 3 and 8, in place. (★☆☆) 72 | 73 | #### 26. What is the output of the following script? (★☆☆) 74 | ```python 75 | # Author: Jake VanderPlas 76 | 77 | print(sum(range(5),-1)) 78 | from numpy import * 79 | print(sum(range(5),-1)) 80 | ``` 81 | 82 | #### 27. Consider an integer vector Z, which of these expressions are legal? (★☆☆) 83 | ```python 84 | Z**Z 85 | 2 << Z >> 2 86 | Z <- Z 87 | 1j*Z 88 | Z/1/1 89 | ZZ 90 | ``` 91 | 92 | #### 28. What are the result of the following expressions? (★☆☆) 93 | ```python 94 | np.array(0) / np.array(0) 95 | np.array(0) // np.array(0) 96 | np.array([np.nan]).astype(int).astype(float) 97 | ``` 98 | 99 | #### 29. How to round away from zero a float array ? (★☆☆) 100 | 101 | #### 30. How to find common values between two arrays? (★☆☆) 102 | 103 | #### 31. How to ignore all numpy warnings (not recommended)? (★☆☆) 104 | 105 | #### 32. Is the following expressions true? (★☆☆) 106 | ```python 107 | np.sqrt(-1) == np.emath.sqrt(-1) 108 | ``` 109 | 110 | #### 33. How to get the dates of yesterday, today and tomorrow? (★☆☆) 111 | 112 | #### 34. How to get all the dates corresponding to the month of July 2016? (★★☆) 113 | 114 | #### 35. How to compute ((A+B)*(-A/2)) in place (without copy)? (★★☆) 115 | 116 | #### 36. Extract the integer part of a random array of positive numbers using 4 different methods (★★☆) 117 | 118 | #### 37. Create a 5x5 matrix with row values ranging from 0 to 4 (★★☆) 119 | 120 | #### 38. Consider a generator function that generates 10 integers and use it to build an array (★☆☆) 121 | 122 | #### 39. Create a vector of size 10 with values ranging from 0 to 1, both excluded (★★☆) 123 | 124 | #### 40. Create a random vector of size 10 and sort it (★★☆) 125 | 126 | #### 41. How to sum a small array faster than np.sum? (★★☆) 127 | 128 | #### 42. Consider two random arrays A and B, check if they are equal (★★☆) 129 | 130 | #### 43. Make an array immutable (read-only) (★★☆) 131 | 132 | #### 44. Consider a random 10x2 matrix representing cartesian coordinates, convert them to polar coordinates (★★☆) 133 | 134 | #### 45. Create random vector of size 10 and replace the maximum value by 0 (★★☆) 135 | 136 | #### 46. Create a structured array with `x` and `y` coordinates covering the [0,1]x[0,1] area (★★☆) 137 | 138 | #### 47. Given two arrays, X and Y, construct the Cauchy matrix C (Cij =1/(xi - yj)) (★★☆) 139 | 140 | #### 48. Print the minimum and maximum representable values for each numpy scalar type (★★☆) 141 | 142 | #### 49. How to print all the values of an array? (★★☆) 143 | 144 | #### 50. How to find the closest value (to a given scalar) in a vector? (★★☆) 145 | 146 | #### 51. Create a structured array representing a position (x,y) and a color (r,g,b) (★★☆) 147 | 148 | #### 52. Consider a random vector with shape (100,2) representing coordinates, find point by point distances (★★☆) 149 | 150 | #### 53. How to convert a float (32 bits) array into an integer (32 bits) array in place? 151 | 152 | #### 54. How to read the following file? (★★☆) 153 | ``` 154 | 1, 2, 3, 4, 5 155 | 6, , , 7, 8 156 | , , 9,10,11 157 | ``` 158 | 159 | #### 55. What is the equivalent of enumerate for numpy arrays? (★★☆) 160 | 161 | #### 56. Generate a generic 2D Gaussian-like array (★★☆) 162 | 163 | #### 57. How to randomly place p elements in a 2D array? (★★☆) 164 | 165 | #### 58. Subtract the mean of each row of a matrix (★★☆) 166 | 167 | #### 59. How to sort an array by the nth column? (★★☆) 168 | 169 | #### 60. How to tell if a given 2D array has null columns? (★★☆) 170 | 171 | #### 61. Find the nearest value from a given value in an array (★★☆) 172 | 173 | #### 62. Considering two arrays with shape (1,3) and (3,1), how to compute their sum using an iterator? (★★☆) 174 | 175 | #### 63. Create an array class that has a name attribute (★★☆) 176 | 177 | #### 64. Consider a given vector, how to add 1 to each element indexed by a second vector (be careful with repeated indices)? (★★★) 178 | 179 | #### 65. How to accumulate elements of a vector (X) to an array (F) based on an index list (I)? (★★★) 180 | 181 | #### 66. Considering a (w,h,3) image of (dtype=ubyte), compute the number of unique colors (★★☆) 182 | 183 | #### 67. Considering a four dimensions array, how to get sum over the last two axis at once? (★★★) 184 | 185 | #### 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? (★★★) 186 | 187 | #### 69. How to get the diagonal of a dot product? (★★★) 188 | 189 | #### 70. Consider the vector [1, 2, 3, 4, 5], how to build a new vector with 3 consecutive zeros interleaved between each value? (★★★) 190 | 191 | #### 71. Consider an array of dimension (5,5,3), how to multiply it by an array with dimensions (5,5)? (★★★) 192 | 193 | #### 72. How to swap two rows of an array? (★★★) 194 | 195 | #### 73. Consider a set of 10 triplets describing 10 triangles (with shared vertices), find the set of unique line segments composing all the triangles (★★★) 196 | 197 | #### 74. Given a sorted array C that corresponds to a bincount, how to produce an array A such that np.bincount(A) == C? (★★★) 198 | 199 | #### 75. How to compute averages using a sliding window over an array? (★★★) 200 | 201 | #### 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]) (★★★) 202 | 203 | #### 77. How to negate a boolean, or to change the sign of a float inplace? (★★★) 204 | 205 | #### 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])? (★★★) 206 | 207 | #### 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])? (★★★) 208 | 209 | #### 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) (★★★) 210 | 211 | #### 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]]? (★★★) 212 | 213 | #### 82. Compute a matrix rank (★★★) 214 | 215 | #### 83. How to find the most frequent value in an array? 216 | 217 | #### 84. Extract all the contiguous 3x3 blocks from a random 10x10 matrix (★★★) 218 | 219 | #### 85. Create a 2D array subclass such that Z[i,j] == Z[j,i] (★★★) 220 | 221 | #### 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)) (★★★) 222 | 223 | #### 87. Consider a 16x16 array, how to get the block-sum (block size is 4x4)? (★★★) 224 | 225 | #### 88. How to implement the Game of Life using numpy arrays? (★★★) 226 | 227 | #### 89. How to get the n largest values of an array (★★★) 228 | 229 | #### 90. Given an arbitrary number of vectors, build the cartesian product (every combination of every item) (★★★) 230 | 231 | #### 91. How to create a record array from a regular array? (★★★) 232 | 233 | #### 92. Consider a large vector Z, compute Z to the power of 3 using 3 different methods (★★★) 234 | 235 | #### 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? (★★★) 236 | 237 | #### 94. Considering a 10x3 matrix, extract rows with unequal values (e.g. [2,2,3]) (★★★) 238 | 239 | #### 95. Convert a vector of ints into a matrix binary representation (★★★) 240 | 241 | #### 96. Given a two dimensional array, how to extract unique rows? (★★★) 242 | 243 | #### 97. Considering 2 vectors A & B, write the einsum equivalent of inner, outer, sum, and mul function (★★★) 244 | 245 | #### 98. Considering a path described by two vectors (X,Y), how to sample it using equidistant samples (★★★)? 246 | 247 | #### 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. (★★★) 248 | 249 | #### 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). (★★★) 250 | -------------------------------------------------------------------------------- /100_Numpy_exercises_with_hints.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | # 100 numpy exercises 5 | 6 | This is a collection of exercises that have been collected in the numpy mailing list, on stack overflow 7 | and in the numpy documentation. The goal of this collection is to offer a quick reference for both old 8 | and new users but also to provide a set of exercises for those who teach. 9 | 10 | 11 | If you find an error or think you've a better way to solve some of them, feel 12 | free to open an issue at . 13 | File automatically generated. See the documentation to update questions/answers/hints programmatically. 14 | 15 | #### 1. Import the numpy package under the name `np` (★☆☆) 16 | `hint: import … as` 17 | #### 2. Print the numpy version and the configuration (★☆☆) 18 | `hint: np.__version__, np.show_config)` 19 | #### 3. Create a null vector of size 10 (★☆☆) 20 | `hint: np.zeros` 21 | #### 4. How to find the memory size of any array (★☆☆) 22 | `hint: size, itemsize` 23 | #### 5. How to get the documentation of the numpy add function from the command line? (★☆☆) 24 | `hint: np.info` 25 | #### 6. Create a null vector of size 10 but the fifth value which is 1 (★☆☆) 26 | `hint: array[4]` 27 | #### 7. Create a vector with values ranging from 10 to 49 (★☆☆) 28 | `hint: arange` 29 | #### 8. Reverse a vector (first element becomes last) (★☆☆) 30 | `hint: array[::-1]` 31 | #### 9. Create a 3x3 matrix with values ranging from 0 to 8 (★☆☆) 32 | `hint: reshape` 33 | #### 10. Find indices of non-zero elements from [1,2,0,0,4,0] (★☆☆) 34 | `hint: np.nonzero` 35 | #### 11. Create a 3x3 identity matrix (★☆☆) 36 | `hint: np.eye` 37 | #### 12. Create a 3x3x3 array with random values (★☆☆) 38 | `hint: np.random.random` 39 | #### 13. Create a 10x10 array with random values and find the minimum and maximum values (★☆☆) 40 | `hint: min, max` 41 | #### 14. Create a random vector of size 30 and find the mean value (★☆☆) 42 | `hint: mean` 43 | #### 15. Create a 2d array with 1 on the border and 0 inside (★☆☆) 44 | `hint: array[1:-1, 1:-1]` 45 | #### 16. How to add a border (filled with 0's) around an existing array? (★☆☆) 46 | `hint: np.pad` 47 | #### 17. What is the result of the following expression? (★☆☆) 48 | ```python 49 | 0 * np.nan 50 | np.nan == np.nan 51 | np.inf > np.nan 52 | np.nan - np.nan 53 | np.nan in set([np.nan]) 54 | 0.3 == 3 * 0.1 55 | ``` 56 | `hint: NaN = not a number, inf = infinity` 57 | #### 18. Create a 5x5 matrix with values 1,2,3,4 just below the diagonal (★☆☆) 58 | `hint: np.diag` 59 | #### 19. Create a 8x8 matrix and fill it with a checkerboard pattern (★☆☆) 60 | `hint: array[::2]` 61 | #### 20. Consider a (6,7,8) shape array, what is the index (x,y,z) of the 100th element? (★☆☆) 62 | `hint: np.unravel_index` 63 | #### 21. Create a checkerboard 8x8 matrix using the tile function (★☆☆) 64 | `hint: np.tile` 65 | #### 22. Normalize a 5x5 random matrix (★☆☆) 66 | `hint: (x -mean)/std` 67 | #### 23. Create a custom dtype that describes a color as four unsigned bytes (RGBA) (★☆☆) 68 | `hint: np.dtype` 69 | #### 24. Multiply a 5x3 matrix by a 3x2 matrix (real matrix product) (★☆☆) 70 | `hint:` 71 | #### 25. Given a 1D array, negate all elements which are between 3 and 8, in place. (★☆☆) 72 | `hint: >, <` 73 | #### 26. What is the output of the following script? (★☆☆) 74 | ```python 75 | # Author: Jake VanderPlas 76 | 77 | print(sum(range(5),-1)) 78 | from numpy import * 79 | print(sum(range(5),-1)) 80 | ``` 81 | `hint: np.sum` 82 | #### 27. Consider an integer vector Z, which of these expressions are legal? (★☆☆) 83 | ```python 84 | Z**Z 85 | 2 << Z >> 2 86 | Z <- Z 87 | 1j*Z 88 | Z/1/1 89 | ZZ 90 | ``` 91 | `No hints provided...` 92 | #### 28. What are the result of the following expressions? (★☆☆) 93 | ```python 94 | np.array(0) / np.array(0) 95 | np.array(0) // np.array(0) 96 | np.array([np.nan]).astype(int).astype(float) 97 | ``` 98 | `No hints provided...` 99 | #### 29. How to round away from zero a float array ? (★☆☆) 100 | `hint: np.uniform, np.copysign, np.ceil, np.abs, np.where` 101 | #### 30. How to find common values between two arrays? (★☆☆) 102 | `hint: np.intersect1d` 103 | #### 31. How to ignore all numpy warnings (not recommended)? (★☆☆) 104 | `hint: np.seterr, np.errstate` 105 | #### 32. Is the following expressions true? (★☆☆) 106 | ```python 107 | np.sqrt(-1) == np.emath.sqrt(-1) 108 | ``` 109 | `hint: imaginary number` 110 | #### 33. How to get the dates of yesterday, today and tomorrow? (★☆☆) 111 | `hint: np.datetime64, np.timedelta64` 112 | #### 34. How to get all the dates corresponding to the month of July 2016? (★★☆) 113 | `hint: np.arange(dtype=datetime64['D'])` 114 | #### 35. How to compute ((A+B)*(-A/2)) in place (without copy)? (★★☆) 115 | `hint: np.add(out=), np.negative(out=), np.multiply(out=), np.divide(out=)` 116 | #### 36. Extract the integer part of a random array of positive numbers using 4 different methods (★★☆) 117 | `hint: %, np.floor, astype, np.trunc` 118 | #### 37. Create a 5x5 matrix with row values ranging from 0 to 4 (★★☆) 119 | `hint: np.arange` 120 | #### 38. Consider a generator function that generates 10 integers and use it to build an array (★☆☆) 121 | `hint: np.fromiter` 122 | #### 39. Create a vector of size 10 with values ranging from 0 to 1, both excluded (★★☆) 123 | `hint: np.linspace` 124 | #### 40. Create a random vector of size 10 and sort it (★★☆) 125 | `hint: sort` 126 | #### 41. How to sum a small array faster than np.sum? (★★☆) 127 | `hint: np.add.reduce` 128 | #### 42. Consider two random arrays A and B, check if they are equal (★★☆) 129 | `hint: np.allclose, np.array_equal` 130 | #### 43. Make an array immutable (read-only) (★★☆) 131 | `hint: flags.writeable` 132 | #### 44. Consider a random 10x2 matrix representing cartesian coordinates, convert them to polar coordinates (★★☆) 133 | `hint: np.sqrt, np.arctan2` 134 | #### 45. Create random vector of size 10 and replace the maximum value by 0 (★★☆) 135 | `hint: argmax` 136 | #### 46. Create a structured array with `x` and `y` coordinates covering the [0,1]x[0,1] area (★★☆) 137 | `hint: np.meshgrid` 138 | #### 47. Given two arrays, X and Y, construct the Cauchy matrix C (Cij =1/(xi - yj)) (★★☆) 139 | `hint: np.subtract.outer` 140 | #### 48. Print the minimum and maximum representable values for each numpy scalar type (★★☆) 141 | `hint: np.iinfo, np.finfo, eps` 142 | #### 49. How to print all the values of an array? (★★☆) 143 | `hint: np.set_printoptions` 144 | #### 50. How to find the closest value (to a given scalar) in a vector? (★★☆) 145 | `hint: argmin` 146 | #### 51. Create a structured array representing a position (x,y) and a color (r,g,b) (★★☆) 147 | `hint: dtype` 148 | #### 52. Consider a random vector with shape (100,2) representing coordinates, find point by point distances (★★☆) 149 | `hint: np.atleast_2d, T, np.sqrt` 150 | #### 53. How to convert a float (32 bits) array into an integer (32 bits) array in place? 151 | `hint: view and [:] =` 152 | #### 54. How to read the following file? (★★☆) 153 | ``` 154 | 1, 2, 3, 4, 5 155 | 6, , , 7, 8 156 | , , 9,10,11 157 | ``` 158 | `hint: np.genfromtxt` 159 | #### 55. What is the equivalent of enumerate for numpy arrays? (★★☆) 160 | `hint: np.ndenumerate, np.ndindex` 161 | #### 56. Generate a generic 2D Gaussian-like array (★★☆) 162 | `hint: np.meshgrid, np.exp` 163 | #### 57. How to randomly place p elements in a 2D array? (★★☆) 164 | `hint: np.put, np.random.choice` 165 | #### 58. Subtract the mean of each row of a matrix (★★☆) 166 | `hint: mean(axis=,keepdims=)` 167 | #### 59. How to sort an array by the nth column? (★★☆) 168 | `hint: argsort` 169 | #### 60. How to tell if a given 2D array has null columns? (★★☆) 170 | `hint: any, ~` 171 | #### 61. Find the nearest value from a given value in an array (★★☆) 172 | `hint: np.abs, argmin, flat` 173 | #### 62. Considering two arrays with shape (1,3) and (3,1), how to compute their sum using an iterator? (★★☆) 174 | `hint: np.nditer` 175 | #### 63. Create an array class that has a name attribute (★★☆) 176 | `hint: class method` 177 | #### 64. Consider a given vector, how to add 1 to each element indexed by a second vector (be careful with repeated indices)? (★★★) 178 | `hint: np.bincount | np.add.at` 179 | #### 65. How to accumulate elements of a vector (X) to an array (F) based on an index list (I)? (★★★) 180 | `hint: np.bincount` 181 | #### 66. Considering a (w,h,3) image of (dtype=ubyte), compute the number of unique colors (★★☆) 182 | `hint: np.unique` 183 | #### 67. Considering a four dimensions array, how to get sum over the last two axis at once? (★★★) 184 | `hint: sum(axis=(-2,-1))` 185 | #### 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? (★★★) 186 | `hint: np.bincount` 187 | #### 69. How to get the diagonal of a dot product? (★★★) 188 | `hint: np.diag` 189 | #### 70. Consider the vector [1, 2, 3, 4, 5], how to build a new vector with 3 consecutive zeros interleaved between each value? (★★★) 190 | `hint: array[::4]` 191 | #### 71. Consider an array of dimension (5,5,3), how to multiply it by an array with dimensions (5,5)? (★★★) 192 | `hint: array[:, :, None]` 193 | #### 72. How to swap two rows of an array? (★★★) 194 | `hint: array[[]] = array[[]]` 195 | #### 73. Consider a set of 10 triplets describing 10 triangles (with shared vertices), find the set of unique line segments composing all the triangles (★★★) 196 | `hint: repeat, np.roll, np.sort, view, np.unique` 197 | #### 74. Given a sorted array C that corresponds to a bincount, how to produce an array A such that np.bincount(A) == C? (★★★) 198 | `hint: np.repeat` 199 | #### 75. How to compute averages using a sliding window over an array? (★★★) 200 | `hint: np.cumsum, from numpy.lib.stride_tricks import sliding_window_view (np>=1.20.0)` 201 | #### 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]) (★★★) 202 | `hint: from numpy.lib import stride_tricks, from numpy.lib.stride_tricks import sliding_window_view (np>=1.20.0)` 203 | #### 77. How to negate a boolean, or to change the sign of a float inplace? (★★★) 204 | `hint: np.logical_not, np.negative` 205 | #### 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])? (★★★) 206 | `No hints provided...` 207 | #### 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])? (★★★) 208 | `No hints provided...` 209 | #### 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) (★★★) 210 | `hint: minimum maximum` 211 | #### 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]]? (★★★) 212 | `hint: stride_tricks.as_strided, from numpy.lib.stride_tricks import sliding_window_view (np>=1.20.0)` 213 | #### 82. Compute a matrix rank (★★★) 214 | `hint: np.linalg.svd, np.linalg.matrix_rank` 215 | #### 83. How to find the most frequent value in an array? 216 | `hint: np.bincount, argmax` 217 | #### 84. Extract all the contiguous 3x3 blocks from a random 10x10 matrix (★★★) 218 | `hint: stride_tricks.as_strided, from numpy.lib.stride_tricks import sliding_window_view (np>=1.20.0)` 219 | #### 85. Create a 2D array subclass such that Z[i,j] == Z[j,i] (★★★) 220 | `hint: class method` 221 | #### 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)) (★★★) 222 | `hint: np.tensordot` 223 | #### 87. Consider a 16x16 array, how to get the block-sum (block size is 4x4)? (★★★) 224 | `hint: np.add.reduceat, from numpy.lib.stride_tricks import sliding_window_view (np>=1.20.0)` 225 | #### 88. How to implement the Game of Life using numpy arrays? (★★★) 226 | `No hints provided...` 227 | #### 89. How to get the n largest values of an array (★★★) 228 | `hint: np.argsort | np.argpartition` 229 | #### 90. Given an arbitrary number of vectors, build the cartesian product (every combination of every item) (★★★) 230 | `hint: np.indices` 231 | #### 91. How to create a record array from a regular array? (★★★) 232 | `hint: np.core.records.fromarrays` 233 | #### 92. Consider a large vector Z, compute Z to the power of 3 using 3 different methods (★★★) 234 | `hint: np.power, *, np.einsum` 235 | #### 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? (★★★) 236 | `hint: np.where` 237 | #### 94. Considering a 10x3 matrix, extract rows with unequal values (e.g. [2,2,3]) (★★★) 238 | `No hints provided...` 239 | #### 95. Convert a vector of ints into a matrix binary representation (★★★) 240 | `hint: np.unpackbits` 241 | #### 96. Given a two dimensional array, how to extract unique rows? (★★★) 242 | `hint: np.ascontiguousarray | np.unique` 243 | #### 97. Considering 2 vectors A & B, write the einsum equivalent of inner, outer, sum, and mul function (★★★) 244 | `hint: np.einsum` 245 | #### 98. Considering a path described by two vectors (X,Y), how to sample it using equidistant samples (★★★)? 246 | `hint: np.cumsum, np.interp` 247 | #### 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. (★★★) 248 | `hint: np.logical_and.reduce, np.mod` 249 | #### 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). (★★★) 250 | `hint: np.percentile` -------------------------------------------------------------------------------- /100_Numpy_exercises_with_hints_with_solutions.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | # 100 numpy exercises 5 | 6 | This is a collection of exercises that have been collected in the numpy mailing list, on stack overflow 7 | and in the numpy documentation. The goal of this collection is to offer a quick reference for both old 8 | and new users but also to provide a set of exercises for those who teach. 9 | 10 | 11 | If you find an error or think you've a better way to solve some of them, feel 12 | free to open an issue at . 13 | File automatically generated. See the documentation to update questions/answers/hints programmatically. 14 | 15 | #### 1. Import the numpy package under the name `np` (★☆☆) 16 | `hint: import … as` 17 | 18 | ```python 19 | import numpy as np 20 | ``` 21 | #### 2. Print the numpy version and the configuration (★☆☆) 22 | `hint: np.__version__, np.show_config)` 23 | 24 | ```python 25 | print(np.__version__) 26 | np.show_config() 27 | ``` 28 | #### 3. Create a null vector of size 10 (★☆☆) 29 | `hint: np.zeros` 30 | 31 | ```python 32 | Z = np.zeros(10) 33 | print(Z) 34 | ``` 35 | #### 4. How to find the memory size of any array (★☆☆) 36 | `hint: size, itemsize` 37 | 38 | ```python 39 | Z = np.zeros((10,10)) 40 | print("%d bytes" % (Z.size * Z.itemsize)) 41 | ``` 42 | #### 5. How to get the documentation of the numpy add function from the command line? (★☆☆) 43 | `hint: np.info` 44 | 45 | ```python 46 | %run `python -c "import numpy; numpy.info(numpy.add)"` 47 | ``` 48 | #### 6. Create a null vector of size 10 but the fifth value which is 1 (★☆☆) 49 | `hint: array[4]` 50 | 51 | ```python 52 | Z = np.zeros(10) 53 | Z[4] = 1 54 | print(Z) 55 | ``` 56 | #### 7. Create a vector with values ranging from 10 to 49 (★☆☆) 57 | `hint: arange` 58 | 59 | ```python 60 | Z = np.arange(10,50) 61 | print(Z) 62 | ``` 63 | #### 8. Reverse a vector (first element becomes last) (★☆☆) 64 | `hint: array[::-1]` 65 | 66 | ```python 67 | Z = np.arange(50) 68 | Z = Z[::-1] 69 | print(Z) 70 | ``` 71 | #### 9. Create a 3x3 matrix with values ranging from 0 to 8 (★☆☆) 72 | `hint: reshape` 73 | 74 | ```python 75 | Z = np.arange(9).reshape(3, 3) 76 | print(Z) 77 | ``` 78 | #### 10. Find indices of non-zero elements from [1,2,0,0,4,0] (★☆☆) 79 | `hint: np.nonzero` 80 | 81 | ```python 82 | nz = np.nonzero([1,2,0,0,4,0]) 83 | print(nz) 84 | ``` 85 | #### 11. Create a 3x3 identity matrix (★☆☆) 86 | `hint: np.eye` 87 | 88 | ```python 89 | Z = np.eye(3) 90 | print(Z) 91 | ``` 92 | #### 12. Create a 3x3x3 array with random values (★☆☆) 93 | `hint: np.random.random` 94 | 95 | ```python 96 | Z = np.random.random((3,3,3)) 97 | print(Z) 98 | ``` 99 | `hint: np.random.default_rng().random` 100 | ```python 101 | # Author: KnightSnape 102 | 103 | rng = np.random.default_rng() 104 | Z = rng.random((3, 3, 3)) 105 | print(Z) 106 | ``` 107 | 108 | #### 13. Create a 10x10 array with random values and find the minimum and maximum values (★☆☆) 109 | `hint: min, max` 110 | 111 | ```python 112 | Z = np.random.random((10,10)) 113 | Zmin, Zmax = Z.min(), Z.max() 114 | print(Zmin, Zmax) 115 | ``` 116 | #### 14. Create a random vector of size 30 and find the mean value (★☆☆) 117 | `hint: mean` 118 | 119 | ```python 120 | Z = np.random.random(30) 121 | m = Z.mean() 122 | print(m) 123 | ``` 124 | #### 15. Create a 2d array with 1 on the border and 0 inside (★☆☆) 125 | `hint: array[1:-1, 1:-1]` 126 | 127 | ```python 128 | Z = np.ones((10,10)) 129 | Z[1:-1,1:-1] = 0 130 | print(Z) 131 | ``` 132 | #### 16. How to add a border (filled with 0's) around an existing array? (★☆☆) 133 | `hint: np.pad` 134 | 135 | ```python 136 | Z = np.ones((5,5)) 137 | Z = np.pad(Z, pad_width=1, mode='constant', constant_values=0) 138 | print(Z) 139 | 140 | # Using fancy indexing 141 | Z[:, [0, -1]] = 0 142 | Z[[0, -1], :] = 0 143 | print(Z) 144 | ``` 145 | #### 17. What is the result of the following expression? (★☆☆) 146 | ```python 147 | 0 * np.nan 148 | np.nan == np.nan 149 | np.inf > np.nan 150 | np.nan - np.nan 151 | np.nan in set([np.nan]) 152 | 0.3 == 3 * 0.1 153 | ``` 154 | `hint: NaN = not a number, inf = infinity` 155 | 156 | ```python 157 | print(0 * np.nan) 158 | print(np.nan == np.nan) 159 | print(np.inf > np.nan) 160 | print(np.nan - np.nan) 161 | print(np.nan in set([np.nan])) 162 | print(0.3 == 3 * 0.1) 163 | ``` 164 | #### 18. Create a 5x5 matrix with values 1,2,3,4 just below the diagonal (★☆☆) 165 | `hint: np.diag` 166 | 167 | ```python 168 | Z = np.diag(1+np.arange(4),k=-1) 169 | print(Z) 170 | ``` 171 | #### 19. Create a 8x8 matrix and fill it with a checkerboard pattern (★☆☆) 172 | `hint: array[::2]` 173 | 174 | ```python 175 | Z = np.zeros((8,8),dtype=int) 176 | Z[1::2,::2] = 1 177 | Z[::2,1::2] = 1 178 | print(Z) 179 | ``` 180 | #### 20. Consider a (6,7,8) shape array, what is the index (x,y,z) of the 100th element? (★☆☆) 181 | `hint: np.unravel_index` 182 | 183 | ```python 184 | print(np.unravel_index(99,(6,7,8))) 185 | ``` 186 | #### 21. Create a checkerboard 8x8 matrix using the tile function (★☆☆) 187 | `hint: np.tile` 188 | 189 | ```python 190 | Z = np.tile( np.array([[0,1],[1,0]]), (4,4)) 191 | print(Z) 192 | ``` 193 | #### 22. Normalize a 5x5 random matrix (★☆☆) 194 | `hint: (x -mean)/std` 195 | 196 | ```python 197 | Z = np.random.random((5,5)) 198 | Z = (Z - np.mean (Z)) / (np.std (Z)) 199 | print(Z) 200 | ``` 201 | #### 23. Create a custom dtype that describes a color as four unsigned bytes (RGBA) (★☆☆) 202 | `hint: np.dtype` 203 | 204 | ```python 205 | color = np.dtype([("r", np.ubyte), 206 | ("g", np.ubyte), 207 | ("b", np.ubyte), 208 | ("a", np.ubyte)]) 209 | ``` 210 | #### 24. Multiply a 5x3 matrix by a 3x2 matrix (real matrix product) (★☆☆) 211 | `hint:` 212 | 213 | ```python 214 | Z = np.matmul(np.ones((5, 3)), np.ones((3, 2))) 215 | print(Z) 216 | 217 | # Alternative solution, in Python 3.5 and above 218 | Z = np.ones((5,3)) @ np.ones((3,2)) 219 | print(Z) 220 | ``` 221 | #### 25. Given a 1D array, negate all elements which are between 3 and 8, in place. (★☆☆) 222 | `hint: >, <` 223 | 224 | ```python 225 | # Author: Evgeni Burovski 226 | 227 | Z = np.arange(11) 228 | Z[(3 < Z) & (Z < 8)] *= -1 229 | print(Z) 230 | ``` 231 | #### 26. What is the output of the following script? (★☆☆) 232 | ```python 233 | # Author: Jake VanderPlas 234 | 235 | print(sum(range(5),-1)) 236 | from numpy import * 237 | print(sum(range(5),-1)) 238 | ``` 239 | `hint: np.sum` 240 | 241 | ```python 242 | # Author: Jake VanderPlas 243 | 244 | print(sum(range(5),-1)) 245 | from numpy import * 246 | print(sum(range(5),-1)) 247 | ``` 248 | #### 27. Consider an integer vector Z, which of these expressions are legal? (★☆☆) 249 | ```python 250 | Z**Z 251 | 2 << Z >> 2 252 | Z <- Z 253 | 1j*Z 254 | Z/1/1 255 | ZZ 256 | ``` 257 | `No hints provided...` 258 | 259 | ```python 260 | Z**Z 261 | 2 << Z >> 2 262 | Z <- Z 263 | 1j*Z 264 | Z/1/1 265 | ZZ 266 | ``` 267 | #### 28. What are the result of the following expressions? (★☆☆) 268 | ```python 269 | np.array(0) / np.array(0) 270 | np.array(0) // np.array(0) 271 | np.array([np.nan]).astype(int).astype(float) 272 | ``` 273 | `No hints provided...` 274 | 275 | ```python 276 | print(np.array(0) / np.array(0)) 277 | print(np.array(0) // np.array(0)) 278 | print(np.array([np.nan]).astype(int).astype(float)) 279 | ``` 280 | #### 29. How to round away from zero a float array ? (★☆☆) 281 | `hint: np.uniform, np.copysign, np.ceil, np.abs, np.where` 282 | 283 | ```python 284 | # Author: Charles R Harris 285 | 286 | Z = np.random.uniform(-10,+10,10) 287 | print(np.copysign(np.ceil(np.abs(Z)), Z)) 288 | 289 | # More readable but less efficient 290 | print(np.where(Z>0, np.ceil(Z), np.floor(Z))) 291 | ``` 292 | #### 30. How to find common values between two arrays? (★☆☆) 293 | `hint: np.intersect1d` 294 | 295 | ```python 296 | Z1 = np.random.randint(0,10,10) 297 | Z2 = np.random.randint(0,10,10) 298 | print(np.intersect1d(Z1,Z2)) 299 | ``` 300 | #### 31. How to ignore all numpy warnings (not recommended)? (★☆☆) 301 | `hint: np.seterr, np.errstate` 302 | 303 | ```python 304 | # Suicide mode on 305 | defaults = np.seterr(all="ignore") 306 | Z = np.ones(1) / 0 307 | 308 | # Back to sanity 309 | _ = np.seterr(**defaults) 310 | 311 | # Equivalently with a context manager 312 | with np.errstate(all="ignore"): 313 | np.arange(3) / 0 314 | ``` 315 | #### 32. Is the following expressions true? (★☆☆) 316 | ```python 317 | np.sqrt(-1) == np.emath.sqrt(-1) 318 | ``` 319 | `hint: imaginary number` 320 | 321 | ```python 322 | np.sqrt(-1) == np.emath.sqrt(-1) 323 | ``` 324 | #### 33. How to get the dates of yesterday, today and tomorrow? (★☆☆) 325 | `hint: np.datetime64, np.timedelta64` 326 | 327 | ```python 328 | yesterday = np.datetime64('today') - np.timedelta64(1) 329 | today = np.datetime64('today') 330 | tomorrow = np.datetime64('today') + np.timedelta64(1) 331 | ``` 332 | #### 34. How to get all the dates corresponding to the month of July 2016? (★★☆) 333 | `hint: np.arange(dtype=datetime64['D'])` 334 | 335 | ```python 336 | Z = np.arange('2016-07', '2016-08', dtype='datetime64[D]') 337 | print(Z) 338 | ``` 339 | #### 35. How to compute ((A+B)*(-A/2)) in place (without copy)? (★★☆) 340 | `hint: np.add(out=), np.negative(out=), np.multiply(out=), np.divide(out=)` 341 | 342 | ```python 343 | A = np.ones(3)*1 344 | B = np.ones(3)*2 345 | np.add(A,B,out=B) 346 | np.divide(A,2,out=A) 347 | np.negative(A,out=A) 348 | np.multiply(A,B,out=A) 349 | ``` 350 | #### 36. Extract the integer part of a random array of positive numbers using 4 different methods (★★☆) 351 | `hint: %, np.floor, astype, np.trunc` 352 | 353 | ```python 354 | Z = np.random.uniform(0,10,10) 355 | 356 | print(Z - Z%1) 357 | print(Z // 1) 358 | print(np.floor(Z)) 359 | print(Z.astype(int)) 360 | print(np.trunc(Z)) 361 | ``` 362 | #### 37. Create a 5x5 matrix with row values ranging from 0 to 4 (★★☆) 363 | `hint: np.arange` 364 | 365 | ```python 366 | Z = np.zeros((5,5)) 367 | Z += np.arange(5) 368 | print(Z) 369 | 370 | # without broadcasting 371 | Z = np.tile(np.arange(0, 5), (5,1)) 372 | print(Z) 373 | ``` 374 | #### 38. Consider a generator function that generates 10 integers and use it to build an array (★☆☆) 375 | `hint: np.fromiter` 376 | 377 | ```python 378 | def generate(): 379 | for x in range(10): 380 | yield x 381 | Z = np.fromiter(generate(),dtype=float,count=-1) 382 | print(Z) 383 | ``` 384 | #### 39. Create a vector of size 10 with values ranging from 0 to 1, both excluded (★★☆) 385 | `hint: np.linspace` 386 | 387 | ```python 388 | Z = np.linspace(0,1,11,endpoint=False)[1:] 389 | print(Z) 390 | ``` 391 | #### 40. Create a random vector of size 10 and sort it (★★☆) 392 | `hint: sort` 393 | 394 | ```python 395 | Z = np.random.random(10) 396 | Z.sort() 397 | print(Z) 398 | ``` 399 | #### 41. How to sum a small array faster than np.sum? (★★☆) 400 | `hint: np.add.reduce` 401 | 402 | ```python 403 | # Author: Evgeni Burovski 404 | 405 | Z = np.arange(10) 406 | np.add.reduce(Z) 407 | ``` 408 | #### 42. Consider two random arrays A and B, check if they are equal (★★☆) 409 | `hint: np.allclose, np.array_equal` 410 | 411 | ```python 412 | A = np.random.randint(0,2,5) 413 | B = np.random.randint(0,2,5) 414 | 415 | # Assuming identical shape of the arrays and a tolerance for the comparison of values 416 | equal = np.allclose(A,B) 417 | print(equal) 418 | 419 | # Checking both the shape and the element values, no tolerance (values have to be exactly equal) 420 | equal = np.array_equal(A,B) 421 | print(equal) 422 | ``` 423 | #### 43. Make an array immutable (read-only) (★★☆) 424 | `hint: flags.writeable` 425 | 426 | ```python 427 | Z = np.zeros(10) 428 | Z.flags.writeable = False 429 | Z[0] = 1 430 | ``` 431 | #### 44. Consider a random 10x2 matrix representing cartesian coordinates, convert them to polar coordinates (★★☆) 432 | `hint: np.sqrt, np.arctan2` 433 | 434 | ```python 435 | Z = np.random.random((10,2)) 436 | X,Y = Z[:,0], Z[:,1] 437 | R = np.sqrt(X**2+Y**2) 438 | T = np.arctan2(Y,X) 439 | print(R) 440 | print(T) 441 | ``` 442 | #### 45. Create random vector of size 10 and replace the maximum value by 0 (★★☆) 443 | `hint: argmax` 444 | 445 | ```python 446 | Z = np.random.random(10) 447 | Z[Z.argmax()] = 0 448 | print(Z) 449 | ``` 450 | #### 46. Create a structured array with `x` and `y` coordinates covering the [0,1]x[0,1] area (★★☆) 451 | `hint: np.meshgrid` 452 | 453 | ```python 454 | Z = np.zeros((5,5), [('x',float),('y',float)]) 455 | Z['x'], Z['y'] = np.meshgrid(np.linspace(0,1,5), 456 | np.linspace(0,1,5)) 457 | print(Z) 458 | ``` 459 | #### 47. Given two arrays, X and Y, construct the Cauchy matrix C (Cij =1/(xi - yj)) (★★☆) 460 | `hint: np.subtract.outer` 461 | 462 | ```python 463 | # Author: Evgeni Burovski 464 | 465 | X = np.arange(8) 466 | Y = X + 0.5 467 | C = 1.0 / np.subtract.outer(X, Y) 468 | print(np.linalg.det(C)) 469 | ``` 470 | #### 48. Print the minimum and maximum representable values for each numpy scalar type (★★☆) 471 | `hint: np.iinfo, np.finfo, eps` 472 | 473 | ```python 474 | for dtype in [np.int8, np.int32, np.int64]: 475 | print(np.iinfo(dtype).min) 476 | print(np.iinfo(dtype).max) 477 | for dtype in [np.float32, np.float64]: 478 | print(np.finfo(dtype).min) 479 | print(np.finfo(dtype).max) 480 | print(np.finfo(dtype).eps) 481 | ``` 482 | #### 49. How to print all the values of an array? (★★☆) 483 | `hint: np.set_printoptions` 484 | 485 | ```python 486 | np.set_printoptions(threshold=float("inf")) 487 | Z = np.zeros((40,40)) 488 | print(Z) 489 | ``` 490 | #### 50. How to find the closest value (to a given scalar) in a vector? (★★☆) 491 | `hint: argmin` 492 | 493 | ```python 494 | Z = np.arange(100) 495 | v = np.random.uniform(0,100) 496 | index = (np.abs(Z-v)).argmin() 497 | print(Z[index]) 498 | ``` 499 | #### 51. Create a structured array representing a position (x,y) and a color (r,g,b) (★★☆) 500 | `hint: dtype` 501 | 502 | ```python 503 | Z = np.zeros(10, [ ('position', [ ('x', float, 1), 504 | ('y', float, 1)]), 505 | ('color', [ ('r', float, 1), 506 | ('g', float, 1), 507 | ('b', float, 1)])]) 508 | print(Z) 509 | ``` 510 | #### 52. Consider a random vector with shape (100,2) representing coordinates, find point by point distances (★★☆) 511 | `hint: np.atleast_2d, T, np.sqrt` 512 | 513 | ```python 514 | Z = np.random.random((10,2)) 515 | X,Y = np.atleast_2d(Z[:,0], Z[:,1]) 516 | D = np.sqrt( (X-X.T)**2 + (Y-Y.T)**2) 517 | print(D) 518 | 519 | # Much faster with scipy 520 | import scipy 521 | # Thanks Gavin Heverly-Coulson (#issue 1) 522 | import scipy.spatial 523 | 524 | Z = np.random.random((10,2)) 525 | D = scipy.spatial.distance.cdist(Z,Z) 526 | print(D) 527 | ``` 528 | #### 53. How to convert a float (32 bits) array into an integer (32 bits) array in place? 529 | `hint: view and [:] =` 530 | 531 | ```python 532 | # Thanks Vikas (https://stackoverflow.com/a/10622758/5989906) 533 | # & unutbu (https://stackoverflow.com/a/4396247/5989906) 534 | Z = (np.random.rand(10)*100).astype(np.float32) 535 | Y = Z.view(np.int32) 536 | Y[:] = Z 537 | print(Y) 538 | ``` 539 | #### 54. How to read the following file? (★★☆) 540 | ``` 541 | 1, 2, 3, 4, 5 542 | 6, , , 7, 8 543 | , , 9,10,11 544 | ``` 545 | `hint: np.genfromtxt` 546 | 547 | ```python 548 | from io import StringIO 549 | 550 | # Fake file 551 | s = StringIO('''1, 2, 3, 4, 5 552 | 553 | 6, , , 7, 8 554 | 555 | , , 9,10,11 556 | ''') 557 | Z = np.genfromtxt(s, delimiter=",", dtype=np.int) 558 | print(Z) 559 | ``` 560 | #### 55. What is the equivalent of enumerate for numpy arrays? (★★☆) 561 | `hint: np.ndenumerate, np.ndindex` 562 | 563 | ```python 564 | Z = np.arange(9).reshape(3,3) 565 | for index, value in np.ndenumerate(Z): 566 | print(index, value) 567 | for index in np.ndindex(Z.shape): 568 | print(index, Z[index]) 569 | ``` 570 | #### 56. Generate a generic 2D Gaussian-like array (★★☆) 571 | `hint: np.meshgrid, np.exp` 572 | 573 | ```python 574 | X, Y = np.meshgrid(np.linspace(-1,1,10), np.linspace(-1,1,10)) 575 | D = np.sqrt(X*X+Y*Y) 576 | sigma, mu = 1.0, 0.0 577 | G = np.exp(-( (D-mu)**2 / ( 2.0 * sigma**2 ) ) ) 578 | print(G) 579 | ``` 580 | #### 57. How to randomly place p elements in a 2D array? (★★☆) 581 | `hint: np.put, np.random.choice` 582 | 583 | ```python 584 | # Author: Divakar 585 | 586 | n = 10 587 | p = 3 588 | Z = np.zeros((n,n)) 589 | np.put(Z, np.random.choice(range(n*n), p, replace=False),1) 590 | print(Z) 591 | ``` 592 | #### 58. Subtract the mean of each row of a matrix (★★☆) 593 | `hint: mean(axis=,keepdims=)` 594 | 595 | ```python 596 | # Author: Warren Weckesser 597 | 598 | X = np.random.rand(5, 10) 599 | 600 | # Recent versions of numpy 601 | Y = X - X.mean(axis=1, keepdims=True) 602 | 603 | # Older versions of numpy 604 | Y = X - X.mean(axis=1).reshape(-1, 1) 605 | 606 | print(Y) 607 | ``` 608 | #### 59. How to sort an array by the nth column? (★★☆) 609 | `hint: argsort` 610 | 611 | ```python 612 | # Author: Steve Tjoa 613 | 614 | Z = np.random.randint(0,10,(3,3)) 615 | print(Z) 616 | print(Z[Z[:,1].argsort()]) 617 | ``` 618 | #### 60. How to tell if a given 2D array has null columns? (★★☆) 619 | `hint: any, ~` 620 | 621 | ```python 622 | # Author: Warren Weckesser 623 | 624 | # null : 0 625 | Z = np.random.randint(0,3,(3,10)) 626 | print((~Z.any(axis=0)).any()) 627 | 628 | # null : np.nan 629 | Z=np.array([ 630 | [0,1,np.nan], 631 | [1,2,np.nan], 632 | [4,5,np.nan] 633 | ]) 634 | print(np.isnan(Z).all(axis=0)) 635 | ``` 636 | #### 61. Find the nearest value from a given value in an array (★★☆) 637 | `hint: np.abs, argmin, flat` 638 | 639 | ```python 640 | Z = np.random.uniform(0,1,10) 641 | z = 0.5 642 | m = Z.flat[np.abs(Z - z).argmin()] 643 | print(m) 644 | ``` 645 | #### 62. Considering two arrays with shape (1,3) and (3,1), how to compute their sum using an iterator? (★★☆) 646 | `hint: np.nditer` 647 | 648 | ```python 649 | A = np.arange(3).reshape(3,1) 650 | B = np.arange(3).reshape(1,3) 651 | it = np.nditer([A,B,None]) 652 | for x,y,z in it: z[...] = x + y 653 | print(it.operands[2]) 654 | ``` 655 | #### 63. Create an array class that has a name attribute (★★☆) 656 | `hint: class method` 657 | 658 | ```python 659 | class NamedArray(np.ndarray): 660 | def __new__(cls, array, name="no name"): 661 | obj = np.asarray(array).view(cls) 662 | obj.name = name 663 | return obj 664 | def __array_finalize__(self, obj): 665 | if obj is None: return 666 | self.name = getattr(obj, 'name', "no name") 667 | 668 | Z = NamedArray(np.arange(10), "range_10") 669 | print (Z.name) 670 | ``` 671 | #### 64. Consider a given vector, how to add 1 to each element indexed by a second vector (be careful with repeated indices)? (★★★) 672 | `hint: np.bincount | np.add.at` 673 | 674 | ```python 675 | # Author: Brett Olsen 676 | 677 | Z = np.ones(10) 678 | I = np.random.randint(0,len(Z),20) 679 | Z += np.bincount(I, minlength=len(Z)) 680 | print(Z) 681 | 682 | # Another solution 683 | # Author: Bartosz Telenczuk 684 | np.add.at(Z, I, 1) 685 | print(Z) 686 | ``` 687 | #### 65. How to accumulate elements of a vector (X) to an array (F) based on an index list (I)? (★★★) 688 | `hint: np.bincount` 689 | 690 | ```python 691 | # Author: Alan G Isaac 692 | 693 | X = [1,2,3,4,5,6] 694 | I = [1,3,9,3,4,1] 695 | F = np.bincount(I,X) 696 | print(F) 697 | ``` 698 | #### 66. Considering a (w,h,3) image of (dtype=ubyte), compute the number of unique colors (★★☆) 699 | `hint: np.unique` 700 | 701 | ```python 702 | # Author: Fisher Wang 703 | 704 | w, h = 256, 256 705 | I = np.random.randint(0, 4, (h, w, 3)).astype(np.ubyte) 706 | colors = np.unique(I.reshape(-1, 3), axis=0) 707 | n = len(colors) 708 | print(n) 709 | 710 | # Faster version 711 | # Author: Mark Setchell 712 | # https://stackoverflow.com/a/59671950/2836621 713 | 714 | w, h = 256, 256 715 | I = np.random.randint(0,4,(h,w,3), dtype=np.uint8) 716 | 717 | # View each pixel as a single 24-bit integer, rather than three 8-bit bytes 718 | I24 = np.dot(I.astype(np.uint32),[1,256,65536]) 719 | 720 | # Count unique colours 721 | n = len(np.unique(I24)) 722 | print(n) 723 | ``` 724 | #### 67. Considering a four dimensions array, how to get sum over the last two axis at once? (★★★) 725 | `hint: sum(axis=(-2,-1))` 726 | 727 | ```python 728 | A = np.random.randint(0,10,(3,4,3,4)) 729 | # solution by passing a tuple of axes (introduced in numpy 1.7.0) 730 | sum = A.sum(axis=(-2,-1)) 731 | print(sum) 732 | # solution by flattening the last two dimensions into one 733 | # (useful for functions that don't accept tuples for axis argument) 734 | sum = A.reshape(A.shape[:-2] + (-1,)).sum(axis=-1) 735 | print(sum) 736 | ``` 737 | #### 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? (★★★) 738 | `hint: np.bincount` 739 | 740 | ```python 741 | # Author: Jaime Fernández del Río 742 | 743 | D = np.random.uniform(0,1,100) 744 | S = np.random.randint(0,10,100) 745 | D_sums = np.bincount(S, weights=D) 746 | D_counts = np.bincount(S) 747 | D_means = D_sums / D_counts 748 | print(D_means) 749 | 750 | # Pandas solution as a reference due to more intuitive code 751 | import pandas as pd 752 | print(pd.Series(D).groupby(S).mean()) 753 | ``` 754 | #### 69. How to get the diagonal of a dot product? (★★★) 755 | `hint: np.diag` 756 | 757 | ```python 758 | # Author: Mathieu Blondel 759 | 760 | A = np.random.uniform(0,1,(5,5)) 761 | B = np.random.uniform(0,1,(5,5)) 762 | 763 | # Slow version 764 | np.diag(np.dot(A, B)) 765 | 766 | # Fast version 767 | np.sum(A * B.T, axis=1) 768 | 769 | # Faster version 770 | np.einsum("ij,ji->i", A, B) 771 | ``` 772 | #### 70. Consider the vector [1, 2, 3, 4, 5], how to build a new vector with 3 consecutive zeros interleaved between each value? (★★★) 773 | `hint: array[::4]` 774 | 775 | ```python 776 | # Author: Warren Weckesser 777 | 778 | Z = np.array([1,2,3,4,5]) 779 | nz = 3 780 | Z0 = np.zeros(len(Z) + (len(Z)-1)*(nz)) 781 | Z0[::nz+1] = Z 782 | print(Z0) 783 | ``` 784 | #### 71. Consider an array of dimension (5,5,3), how to multiply it by an array with dimensions (5,5)? (★★★) 785 | `hint: array[:, :, None]` 786 | 787 | ```python 788 | A = np.ones((5,5,3)) 789 | B = 2*np.ones((5,5)) 790 | print(A * B[:,:,None]) 791 | ``` 792 | #### 72. How to swap two rows of an array? (★★★) 793 | `hint: array[[]] = array[[]]` 794 | 795 | ```python 796 | # Author: Eelco Hoogendoorn 797 | 798 | A = np.arange(25).reshape(5,5) 799 | A[[0,1]] = A[[1,0]] 800 | print(A) 801 | ``` 802 | #### 73. Consider a set of 10 triplets describing 10 triangles (with shared vertices), find the set of unique line segments composing all the triangles (★★★) 803 | `hint: repeat, np.roll, np.sort, view, np.unique` 804 | 805 | ```python 806 | # Author: Nicolas P. Rougier 807 | 808 | faces = np.random.randint(0,100,(10,3)) 809 | F = np.roll(faces.repeat(2,axis=1),-1,axis=1) 810 | F = F.reshape(len(F)*3,2) 811 | F = np.sort(F,axis=1) 812 | G = F.view( dtype=[('p0',F.dtype),('p1',F.dtype)] ) 813 | G = np.unique(G) 814 | print(G) 815 | ``` 816 | #### 74. Given a sorted array C that corresponds to a bincount, how to produce an array A such that np.bincount(A) == C? (★★★) 817 | `hint: np.repeat` 818 | 819 | ```python 820 | # Author: Jaime Fernández del Río 821 | 822 | C = np.bincount([1,1,2,3,4,4,6]) 823 | A = np.repeat(np.arange(len(C)), C) 824 | print(A) 825 | ``` 826 | #### 75. How to compute averages using a sliding window over an array? (★★★) 827 | `hint: np.cumsum, from numpy.lib.stride_tricks import sliding_window_view (np>=1.20.0)` 828 | 829 | ```python 830 | # Author: Jaime Fernández del Río 831 | 832 | def moving_average(a, n=3) : 833 | ret = np.cumsum(a, dtype=float) 834 | ret[n:] = ret[n:] - ret[:-n] 835 | return ret[n - 1:] / n 836 | Z = np.arange(20) 837 | print(moving_average(Z, n=3)) 838 | 839 | # Author: Jeff Luo (@Jeff1999) 840 | # make sure your NumPy >= 1.20.0 841 | 842 | from numpy.lib.stride_tricks import sliding_window_view 843 | 844 | Z = np.arange(20) 845 | print(sliding_window_view(Z, window_shape=3).mean(axis=-1)) 846 | ``` 847 | #### 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]) (★★★) 848 | `hint: from numpy.lib import stride_tricks, from numpy.lib.stride_tricks import sliding_window_view (np>=1.20.0)` 849 | 850 | ```python 851 | # Author: Joe Kington / Erik Rigtorp 852 | from numpy.lib import stride_tricks 853 | 854 | def rolling(a, window): 855 | shape = (a.size - window + 1, window) 856 | strides = (a.strides[0], a.strides[0]) 857 | return stride_tricks.as_strided(a, shape=shape, strides=strides) 858 | Z = rolling(np.arange(10), 3) 859 | print(Z) 860 | 861 | # Author: Jeff Luo (@Jeff1999) 862 | 863 | Z = np.arange(10) 864 | print(sliding_window_view(Z, window_shape=3)) 865 | ``` 866 | #### 77. How to negate a boolean, or to change the sign of a float inplace? (★★★) 867 | `hint: np.logical_not, np.negative` 868 | 869 | ```python 870 | # Author: Nathaniel J. Smith 871 | 872 | Z = np.random.randint(0,2,100) 873 | np.logical_not(Z, out=Z) 874 | 875 | Z = np.random.uniform(-1.0,1.0,100) 876 | np.negative(Z, out=Z) 877 | ``` 878 | #### 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])? (★★★) 879 | `No hints provided...` 880 | 881 | ```python 882 | def distance(P0, P1, p): 883 | T = P1 - P0 884 | L = (T**2).sum(axis=1) 885 | U = -((P0[:,0]-p[...,0])*T[:,0] + (P0[:,1]-p[...,1])*T[:,1]) / L 886 | U = U.reshape(len(U),1) 887 | D = P0 + U*T - p 888 | return np.sqrt((D**2).sum(axis=1)) 889 | 890 | P0 = np.random.uniform(-10,10,(10,2)) 891 | P1 = np.random.uniform(-10,10,(10,2)) 892 | p = np.random.uniform(-10,10,( 1,2)) 893 | print(distance(P0, P1, p)) 894 | ``` 895 | #### 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])? (★★★) 896 | `No hints provided...` 897 | 898 | ```python 899 | # Author: Italmassov Kuanysh 900 | 901 | # based on distance function from previous question 902 | P0 = np.random.uniform(-10, 10, (10,2)) 903 | P1 = np.random.uniform(-10,10,(10,2)) 904 | p = np.random.uniform(-10, 10, (10,2)) 905 | print(np.array([distance(P0,P1,p_i) for p_i in p])) 906 | 907 | # Author: Yang Wu (Broadcasting) 908 | def distance_points_to_lines(p: np.ndarray, p_1: np.ndarray, p_2: np.ndarray) -> np.ndarray: 909 | x_0, y_0 = p.T # Shape -> (n points, ) 910 | x_1, y_1 = p_1.T # Shape -> (n lines, ) 911 | x_2, y_2 = p_2.T # Shape -> (n lines, ) 912 | 913 | # Displacement vector coordinates from p_1 -> p_2 914 | dx = x_2 - x_1 # Shape -> (n lines, ) 915 | dy = y_2 - y_1 # Shape -> (n lines, ) 916 | 917 | # The 'cross product' term 918 | cross_term = x_2 * y_1 - y_2 * x_1 # Shape -> (n lines, ) 919 | 920 | # Broadcast x_0, y_0 (n points, 1) and dx, dy, cross_term (1, n lines) -> (n points, n lines) 921 | numerator = np.abs( 922 | dy[np.newaxis, :] * x_0[:, np.newaxis] 923 | - dx[np.newaxis, :] * y_0[:, np.newaxis] 924 | + cross_term[np.newaxis, :] 925 | ) 926 | denominator = np.sqrt(dx**2 + dy**2) # Shape -> (n lines, ) 927 | 928 | # Shape (n points, n lines) / (1, n_lines) -> (n points, n lines) 929 | return numerator / denominator[np.newaxis, :] 930 | 931 | distance_points_to_lines(p, P0, P1) 932 | ``` 933 | #### 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) (★★★) 934 | `hint: minimum maximum` 935 | 936 | ```python 937 | # Author: Nicolas Rougier 938 | 939 | Z = np.random.randint(0,10,(10,10)) 940 | shape = (5,5) 941 | fill = 0 942 | position = (1,1) 943 | 944 | R = np.ones(shape, dtype=Z.dtype)*fill 945 | P = np.array(list(position)).astype(int) 946 | Rs = np.array(list(R.shape)).astype(int) 947 | Zs = np.array(list(Z.shape)).astype(int) 948 | 949 | R_start = np.zeros((len(shape),)).astype(int) 950 | R_stop = np.array(list(shape)).astype(int) 951 | Z_start = (P-Rs//2) 952 | Z_stop = (P+Rs//2)+Rs%2 953 | 954 | R_start = (R_start - np.minimum(Z_start,0)).tolist() 955 | Z_start = (np.maximum(Z_start,0)).tolist() 956 | R_stop = np.maximum(R_start, (R_stop - np.maximum(Z_stop-Zs,0))).tolist() 957 | Z_stop = (np.minimum(Z_stop,Zs)).tolist() 958 | 959 | r = [slice(start,stop) for start,stop in zip(R_start,R_stop)] 960 | z = [slice(start,stop) for start,stop in zip(Z_start,Z_stop)] 961 | R[r] = Z[z] 962 | print(Z) 963 | print(R) 964 | ``` 965 | #### 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]]? (★★★) 966 | `hint: stride_tricks.as_strided, from numpy.lib.stride_tricks import sliding_window_view (np>=1.20.0)` 967 | 968 | ```python 969 | # Author: Stefan van der Walt 970 | 971 | Z = np.arange(1,15,dtype=np.uint32) 972 | R = stride_tricks.as_strided(Z,(11,4),(4,4)) 973 | print(R) 974 | 975 | # Author: Jeff Luo (@Jeff1999) 976 | 977 | Z = np.arange(1, 15, dtype=np.uint32) 978 | print(sliding_window_view(Z, window_shape=4)) 979 | ``` 980 | #### 82. Compute a matrix rank (★★★) 981 | `hint: np.linalg.svd, np.linalg.matrix_rank` 982 | 983 | ```python 984 | # Author: Stefan van der Walt 985 | 986 | Z = np.random.uniform(0,1,(10,10)) 987 | U, S, V = np.linalg.svd(Z) # Singular Value Decomposition 988 | rank = np.sum(S > 1e-10) 989 | print(rank) 990 | 991 | # alternative solution: 992 | # Author: Jeff Luo (@Jeff1999) 993 | 994 | rank = np.linalg.matrix_rank(Z) 995 | print(rank) 996 | ``` 997 | #### 83. How to find the most frequent value in an array? 998 | `hint: np.bincount, argmax` 999 | 1000 | ```python 1001 | Z = np.random.randint(0,10,50) 1002 | print(np.bincount(Z).argmax()) 1003 | ``` 1004 | #### 84. Extract all the contiguous 3x3 blocks from a random 10x10 matrix (★★★) 1005 | `hint: stride_tricks.as_strided, from numpy.lib.stride_tricks import sliding_window_view (np>=1.20.0)` 1006 | 1007 | ```python 1008 | # Author: Chris Barker 1009 | 1010 | Z = np.random.randint(0,5,(10,10)) 1011 | n = 3 1012 | i = 1 + (Z.shape[0]-3) 1013 | j = 1 + (Z.shape[1]-3) 1014 | C = stride_tricks.as_strided(Z, shape=(i, j, n, n), strides=Z.strides + Z.strides) 1015 | print(C) 1016 | 1017 | # Author: Jeff Luo (@Jeff1999) 1018 | 1019 | Z = np.random.randint(0,5,(10,10)) 1020 | print(sliding_window_view(Z, window_shape=(3, 3))) 1021 | ``` 1022 | #### 85. Create a 2D array subclass such that Z[i,j] == Z[j,i] (★★★) 1023 | `hint: class method` 1024 | 1025 | ```python 1026 | # Author: Eric O. Lebigot 1027 | # Note: only works for 2d array and value setting using indices 1028 | 1029 | class Symetric(np.ndarray): 1030 | def __setitem__(self, index, value): 1031 | i,j = index 1032 | super(Symetric, self).__setitem__((i,j), value) 1033 | super(Symetric, self).__setitem__((j,i), value) 1034 | 1035 | def symetric(Z): 1036 | return np.asarray(Z + Z.T - np.diag(Z.diagonal())).view(Symetric) 1037 | 1038 | S = symetric(np.random.randint(0,10,(5,5))) 1039 | S[2,3] = 42 1040 | print(S) 1041 | ``` 1042 | #### 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)) (★★★) 1043 | `hint: np.tensordot` 1044 | 1045 | ```python 1046 | # Author: Stefan van der Walt 1047 | 1048 | p, n = 10, 20 1049 | M = np.ones((p,n,n)) 1050 | V = np.ones((p,n,1)) 1051 | S = np.tensordot(M, V, axes=[[0, 2], [0, 1]]) 1052 | print(S) 1053 | 1054 | # It works, because: 1055 | # M is (p,n,n) 1056 | # V is (p,n,1) 1057 | # Thus, summing over the paired axes 0 and 0 (of M and V independently), 1058 | # and 2 and 1, to remain with a (n,1) vector. 1059 | ``` 1060 | #### 87. Consider a 16x16 array, how to get the block-sum (block size is 4x4)? (★★★) 1061 | `hint: np.add.reduceat, from numpy.lib.stride_tricks import sliding_window_view (np>=1.20.0)` 1062 | 1063 | ```python 1064 | # Author: Robert Kern 1065 | 1066 | Z = np.ones((16,16)) 1067 | k = 4 1068 | S = np.add.reduceat(np.add.reduceat(Z, np.arange(0, Z.shape[0], k), axis=0), 1069 | np.arange(0, Z.shape[1], k), axis=1) 1070 | print(S) 1071 | 1072 | # alternative solution: 1073 | # Author: Sebastian Wallkötter (@FirefoxMetzger) 1074 | 1075 | Z = np.ones((16,16)) 1076 | k = 4 1077 | 1078 | windows = np.lib.stride_tricks.sliding_window_view(Z, (k, k)) 1079 | S = windows[::k, ::k, ...].sum(axis=(-2, -1)) 1080 | 1081 | # Author: Jeff Luo (@Jeff1999) 1082 | 1083 | Z = np.ones((16, 16)) 1084 | k = 4 1085 | print(sliding_window_view(Z, window_shape=(k, k))[::k, ::k].sum(axis=(-2, -1))) 1086 | ``` 1087 | #### 88. How to implement the Game of Life using numpy arrays? (★★★) 1088 | `No hints provided...` 1089 | 1090 | ```python 1091 | # Author: Nicolas Rougier 1092 | 1093 | def iterate(Z): 1094 | # Count neighbours 1095 | N = (Z[0:-2,0:-2] + Z[0:-2,1:-1] + Z[0:-2,2:] + 1096 | Z[1:-1,0:-2] + Z[1:-1,2:] + 1097 | Z[2: ,0:-2] + Z[2: ,1:-1] + Z[2: ,2:]) 1098 | 1099 | # Apply rules 1100 | birth = (N==3) & (Z[1:-1,1:-1]==0) 1101 | survive = ((N==2) | (N==3)) & (Z[1:-1,1:-1]==1) 1102 | Z[...] = 0 1103 | Z[1:-1,1:-1][birth | survive] = 1 1104 | return Z 1105 | 1106 | Z = np.random.randint(0,2,(50,50)) 1107 | for i in range(100): Z = iterate(Z) 1108 | print(Z) 1109 | ``` 1110 | #### 89. How to get the n largest values of an array (★★★) 1111 | `hint: np.argsort | np.argpartition` 1112 | 1113 | ```python 1114 | Z = np.arange(10000) 1115 | np.random.shuffle(Z) 1116 | n = 5 1117 | 1118 | # Slow 1119 | print (Z[np.argsort(Z)[-n:]]) 1120 | 1121 | # Fast 1122 | print (Z[np.argpartition(-Z,n)[:n]]) 1123 | ``` 1124 | #### 90. Given an arbitrary number of vectors, build the cartesian product (every combination of every item) (★★★) 1125 | `hint: np.indices` 1126 | 1127 | ```python 1128 | # Author: Stefan Van der Walt 1129 | 1130 | def cartesian(arrays): 1131 | arrays = [np.asarray(a) for a in arrays] 1132 | shape = (len(x) for x in arrays) 1133 | 1134 | ix = np.indices(shape, dtype=int) 1135 | ix = ix.reshape(len(arrays), -1).T 1136 | 1137 | for n, arr in enumerate(arrays): 1138 | ix[:, n] = arrays[n][ix[:, n]] 1139 | 1140 | return ix 1141 | 1142 | print (cartesian(([1, 2, 3], [4, 5], [6, 7]))) 1143 | ``` 1144 | #### 91. How to create a record array from a regular array? (★★★) 1145 | `hint: np.core.records.fromarrays` 1146 | 1147 | ```python 1148 | Z = np.array([("Hello", 2.5, 3), 1149 | ("World", 3.6, 2)]) 1150 | R = np.core.records.fromarrays(Z.T, 1151 | names='col1, col2, col3', 1152 | formats = 'S8, f8, i8') 1153 | print(R) 1154 | ``` 1155 | #### 92. Consider a large vector Z, compute Z to the power of 3 using 3 different methods (★★★) 1156 | `hint: np.power, *, np.einsum` 1157 | 1158 | ```python 1159 | # Author: Ryan G. 1160 | 1161 | x = np.random.rand(int(5e7)) 1162 | 1163 | %timeit np.power(x,3) 1164 | %timeit x*x*x 1165 | %timeit np.einsum('i,i,i->i',x,x,x) 1166 | ``` 1167 | #### 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? (★★★) 1168 | `hint: np.where` 1169 | 1170 | ```python 1171 | # Author: Gabe Schwartz 1172 | 1173 | A = np.random.randint(0,5,(8,3)) 1174 | B = np.random.randint(0,5,(2,2)) 1175 | 1176 | C = (A[..., np.newaxis, np.newaxis] == B) 1177 | rows = np.where(C.any((3,1)).all(1))[0] 1178 | print(rows) 1179 | ``` 1180 | #### 94. Considering a 10x3 matrix, extract rows with unequal values (e.g. [2,2,3]) (★★★) 1181 | `No hints provided...` 1182 | 1183 | ```python 1184 | # Author: Robert Kern 1185 | 1186 | Z = np.random.randint(0,5,(10,3)) 1187 | print(Z) 1188 | # solution for arrays of all dtypes (including string arrays and record arrays) 1189 | E = np.all(Z[:,1:] == Z[:,:-1], axis=1) 1190 | U = Z[~E] 1191 | print(U) 1192 | # soluiton for numerical arrays only, will work for any number of columns in Z 1193 | U = Z[Z.max(axis=1) != Z.min(axis=1),:] 1194 | print(U) 1195 | ``` 1196 | #### 95. Convert a vector of ints into a matrix binary representation (★★★) 1197 | `hint: np.unpackbits` 1198 | 1199 | ```python 1200 | # Author: Warren Weckesser 1201 | 1202 | I = np.array([0, 1, 2, 3, 15, 16, 32, 64, 128]) 1203 | B = ((I.reshape(-1,1) & (2**np.arange(8))) != 0).astype(int) 1204 | print(B[:,::-1]) 1205 | 1206 | # Author: Daniel T. McDonald 1207 | 1208 | I = np.array([0, 1, 2, 3, 15, 16, 32, 64, 128], dtype=np.uint8) 1209 | print(np.unpackbits(I[:, np.newaxis], axis=1)) 1210 | ``` 1211 | #### 96. Given a two dimensional array, how to extract unique rows? (★★★) 1212 | `hint: np.ascontiguousarray | np.unique` 1213 | 1214 | ```python 1215 | # Author: Jaime Fernández del Río 1216 | 1217 | Z = np.random.randint(0,2,(6,3)) 1218 | T = np.ascontiguousarray(Z).view(np.dtype((np.void, Z.dtype.itemsize * Z.shape[1]))) 1219 | _, idx = np.unique(T, return_index=True) 1220 | uZ = Z[idx] 1221 | print(uZ) 1222 | 1223 | # Author: Andreas Kouzelis 1224 | # NumPy >= 1.13 1225 | uZ = np.unique(Z, axis=0) 1226 | print(uZ) 1227 | ``` 1228 | #### 97. Considering 2 vectors A & B, write the einsum equivalent of inner, outer, sum, and mul function (★★★) 1229 | `hint: np.einsum` 1230 | 1231 | ```python 1232 | # Author: Alex Riley 1233 | # Make sure to read: http://ajcr.net/Basic-guide-to-einsum/ 1234 | 1235 | A = np.random.uniform(0,1,10) 1236 | B = np.random.uniform(0,1,10) 1237 | 1238 | np.einsum('i->', A) # np.sum(A) 1239 | np.einsum('i,i->i', A, B) # A * B 1240 | np.einsum('i,i', A, B) # np.inner(A, B) 1241 | np.einsum('i,j->ij', A, B) # np.outer(A, B) 1242 | ``` 1243 | #### 98. Considering a path described by two vectors (X,Y), how to sample it using equidistant samples (★★★)? 1244 | `hint: np.cumsum, np.interp` 1245 | 1246 | ```python 1247 | # Author: Bas Swinckels 1248 | 1249 | phi = np.arange(0, 10*np.pi, 0.1) 1250 | a = 1 1251 | x = a*phi*np.cos(phi) 1252 | y = a*phi*np.sin(phi) 1253 | 1254 | dr = (np.diff(x)**2 + np.diff(y)**2)**.5 # segment lengths 1255 | r = np.zeros_like(x) 1256 | r[1:] = np.cumsum(dr) # integrate path 1257 | r_int = np.linspace(0, r.max(), 200) # regular spaced path 1258 | x_int = np.interp(r_int, r, x) # integrate path 1259 | y_int = np.interp(r_int, r, y) 1260 | ``` 1261 | #### 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. (★★★) 1262 | `hint: np.logical_and.reduce, np.mod` 1263 | 1264 | ```python 1265 | # Author: Evgeni Burovski 1266 | 1267 | X = np.asarray([[1.0, 0.0, 3.0, 8.0], 1268 | [2.0, 0.0, 1.0, 1.0], 1269 | [1.5, 2.5, 1.0, 0.0]]) 1270 | n = 4 1271 | M = np.logical_and.reduce(np.mod(X, 1) == 0, axis=-1) 1272 | M &= (X.sum(axis=-1) == n) 1273 | print(X[M]) 1274 | ``` 1275 | #### 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). (★★★) 1276 | `hint: np.percentile` 1277 | 1278 | ```python 1279 | # Author: Jessica B. Hamrick 1280 | 1281 | X = np.random.randn(100) # random 1D array 1282 | N = 1000 # number of bootstrap samples 1283 | idx = np.random.randint(0, X.size, (N, X.size)) 1284 | means = X[idx].mean(axis=1) 1285 | confint = np.percentile(means, [2.5, 97.5]) 1286 | print(confint) 1287 | ``` -------------------------------------------------------------------------------- /100_Numpy_exercises_with_solutions.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | # 100 numpy exercises 5 | 6 | This is a collection of exercises that have been collected in the numpy mailing list, on stack overflow 7 | and in the numpy documentation. The goal of this collection is to offer a quick reference for both old 8 | and new users but also to provide a set of exercises for those who teach. 9 | 10 | 11 | If you find an error or think you've a better way to solve some of them, feel 12 | free to open an issue at . 13 | File automatically generated. See the documentation to update questions/answers/hints programmatically. 14 | 15 | #### 1. Import the numpy package under the name `np` (★☆☆) 16 | 17 | 18 | ```python 19 | import numpy as np 20 | ``` 21 | #### 2. Print the numpy version and the configuration (★☆☆) 22 | 23 | 24 | ```python 25 | print(np.__version__) 26 | np.show_config() 27 | ``` 28 | #### 3. Create a null vector of size 10 (★☆☆) 29 | 30 | 31 | ```python 32 | Z = np.zeros(10) 33 | print(Z) 34 | ``` 35 | #### 4. How to find the memory size of any array (★☆☆) 36 | 37 | 38 | ```python 39 | Z = np.zeros((10,10)) 40 | print("%d bytes" % (Z.size * Z.itemsize)) 41 | ``` 42 | #### 5. How to get the documentation of the numpy add function from the command line? (★☆☆) 43 | 44 | 45 | ```python 46 | %run `python -c "import numpy; numpy.info(numpy.add)"` 47 | ``` 48 | #### 6. Create a null vector of size 10 but the fifth value which is 1 (★☆☆) 49 | 50 | 51 | ```python 52 | Z = np.zeros(10) 53 | Z[4] = 1 54 | print(Z) 55 | ``` 56 | #### 7. Create a vector with values ranging from 10 to 49 (★☆☆) 57 | 58 | 59 | ```python 60 | Z = np.arange(10,50) 61 | print(Z) 62 | ``` 63 | #### 8. Reverse a vector (first element becomes last) (★☆☆) 64 | 65 | 66 | ```python 67 | Z = np.arange(50) 68 | Z = Z[::-1] 69 | print(Z) 70 | ``` 71 | #### 9. Create a 3x3 matrix with values ranging from 0 to 8 (★☆☆) 72 | 73 | 74 | ```python 75 | Z = np.arange(9).reshape(3, 3) 76 | print(Z) 77 | ``` 78 | #### 10. Find indices of non-zero elements from [1,2,0,0,4,0] (★☆☆) 79 | 80 | 81 | ```python 82 | nz = np.nonzero([1,2,0,0,4,0]) 83 | print(nz) 84 | ``` 85 | #### 11. Create a 3x3 identity matrix (★☆☆) 86 | 87 | 88 | ```python 89 | Z = np.eye(3) 90 | print(Z) 91 | ``` 92 | #### 12. Create a 3x3x3 array with random values (★☆☆) 93 | 94 | 95 | ```python 96 | Z = np.random.random((3,3,3)) 97 | print(Z) 98 | ``` 99 | #### 13. Create a 10x10 array with random values and find the minimum and maximum values (★☆☆) 100 | 101 | 102 | ```python 103 | Z = np.random.random((10,10)) 104 | Zmin, Zmax = Z.min(), Z.max() 105 | print(Zmin, Zmax) 106 | ``` 107 | #### 14. Create a random vector of size 30 and find the mean value (★☆☆) 108 | 109 | 110 | ```python 111 | Z = np.random.random(30) 112 | m = Z.mean() 113 | print(m) 114 | ``` 115 | #### 15. Create a 2d array with 1 on the border and 0 inside (★☆☆) 116 | 117 | 118 | ```python 119 | Z = np.ones((10,10)) 120 | Z[1:-1,1:-1] = 0 121 | print(Z) 122 | ``` 123 | #### 16. How to add a border (filled with 0's) around an existing array? (★☆☆) 124 | 125 | 126 | ```python 127 | Z = np.ones((5,5)) 128 | Z = np.pad(Z, pad_width=1, mode='constant', constant_values=0) 129 | print(Z) 130 | 131 | # Using fancy indexing 132 | Z[:, [0, -1]] = 0 133 | Z[[0, -1], :] = 0 134 | print(Z) 135 | ``` 136 | #### 17. What is the result of the following expression? (★☆☆) 137 | ```python 138 | 0 * np.nan 139 | np.nan == np.nan 140 | np.inf > np.nan 141 | np.nan - np.nan 142 | np.nan in set([np.nan]) 143 | 0.3 == 3 * 0.1 144 | ``` 145 | 146 | 147 | ```python 148 | print(0 * np.nan) 149 | print(np.nan == np.nan) 150 | print(np.inf > np.nan) 151 | print(np.nan - np.nan) 152 | print(np.nan in set([np.nan])) 153 | print(0.3 == 3 * 0.1) 154 | ``` 155 | #### 18. Create a 5x5 matrix with values 1,2,3,4 just below the diagonal (★☆☆) 156 | 157 | 158 | ```python 159 | Z = np.diag(1+np.arange(4),k=-1) 160 | print(Z) 161 | ``` 162 | #### 19. Create a 8x8 matrix and fill it with a checkerboard pattern (★☆☆) 163 | 164 | 165 | ```python 166 | Z = np.zeros((8,8),dtype=int) 167 | Z[1::2,::2] = 1 168 | Z[::2,1::2] = 1 169 | print(Z) 170 | ``` 171 | #### 20. Consider a (6,7,8) shape array, what is the index (x,y,z) of the 100th element? (★☆☆) 172 | 173 | 174 | ```python 175 | print(np.unravel_index(99,(6,7,8))) 176 | ``` 177 | #### 21. Create a checkerboard 8x8 matrix using the tile function (★☆☆) 178 | 179 | 180 | ```python 181 | Z = np.tile( np.array([[0,1],[1,0]]), (4,4)) 182 | print(Z) 183 | ``` 184 | #### 22. Normalize a 5x5 random matrix (★☆☆) 185 | 186 | 187 | ```python 188 | Z = np.random.random((5,5)) 189 | Z = (Z - np.mean (Z)) / (np.std (Z)) 190 | print(Z) 191 | ``` 192 | #### 23. Create a custom dtype that describes a color as four unsigned bytes (RGBA) (★☆☆) 193 | 194 | 195 | ```python 196 | color = np.dtype([("r", np.ubyte), 197 | ("g", np.ubyte), 198 | ("b", np.ubyte), 199 | ("a", np.ubyte)]) 200 | ``` 201 | #### 24. Multiply a 5x3 matrix by a 3x2 matrix (real matrix product) (★☆☆) 202 | 203 | 204 | ```python 205 | Z = np.matmul(np.ones((5, 3)), np.ones((3, 2))) 206 | print(Z) 207 | 208 | # Alternative solution, in Python 3.5 and above 209 | Z = np.ones((5,3)) @ np.ones((3,2)) 210 | print(Z) 211 | ``` 212 | #### 25. Given a 1D array, negate all elements which are between 3 and 8, in place. (★☆☆) 213 | 214 | 215 | ```python 216 | # Author: Evgeni Burovski 217 | 218 | Z = np.arange(11) 219 | Z[(3 < Z) & (Z < 8)] *= -1 220 | print(Z) 221 | ``` 222 | #### 26. What is the output of the following script? (★☆☆) 223 | ```python 224 | # Author: Jake VanderPlas 225 | 226 | print(sum(range(5),-1)) 227 | from numpy import * 228 | print(sum(range(5),-1)) 229 | ``` 230 | 231 | 232 | ```python 233 | # Author: Jake VanderPlas 234 | 235 | print(sum(range(5),-1)) 236 | from numpy import * 237 | print(sum(range(5),-1)) 238 | ``` 239 | #### 27. Consider an integer vector Z, which of these expressions are legal? (★☆☆) 240 | ```python 241 | Z**Z 242 | 2 << Z >> 2 243 | Z <- Z 244 | 1j*Z 245 | Z/1/1 246 | ZZ 247 | ``` 248 | 249 | 250 | ```python 251 | Z**Z 252 | 2 << Z >> 2 253 | Z <- Z 254 | 1j*Z 255 | Z/1/1 256 | ZZ 257 | ``` 258 | #### 28. What are the result of the following expressions? (★☆☆) 259 | ```python 260 | np.array(0) / np.array(0) 261 | np.array(0) // np.array(0) 262 | np.array([np.nan]).astype(int).astype(float) 263 | ``` 264 | 265 | 266 | ```python 267 | print(np.array(0) / np.array(0)) 268 | print(np.array(0) // np.array(0)) 269 | print(np.array([np.nan]).astype(int).astype(float)) 270 | ``` 271 | #### 29. How to round away from zero a float array ? (★☆☆) 272 | 273 | 274 | ```python 275 | # Author: Charles R Harris 276 | 277 | Z = np.random.uniform(-10,+10,10) 278 | print(np.copysign(np.ceil(np.abs(Z)), Z)) 279 | 280 | # More readable but less efficient 281 | print(np.where(Z>0, np.ceil(Z), np.floor(Z))) 282 | ``` 283 | #### 30. How to find common values between two arrays? (★☆☆) 284 | 285 | 286 | ```python 287 | Z1 = np.random.randint(0,10,10) 288 | Z2 = np.random.randint(0,10,10) 289 | print(np.intersect1d(Z1,Z2)) 290 | ``` 291 | #### 31. How to ignore all numpy warnings (not recommended)? (★☆☆) 292 | 293 | 294 | ```python 295 | # Suicide mode on 296 | defaults = np.seterr(all="ignore") 297 | Z = np.ones(1) / 0 298 | 299 | # Back to sanity 300 | _ = np.seterr(**defaults) 301 | 302 | # Equivalently with a context manager 303 | with np.errstate(all="ignore"): 304 | np.arange(3) / 0 305 | ``` 306 | #### 32. Is the following expressions true? (★☆☆) 307 | ```python 308 | np.sqrt(-1) == np.emath.sqrt(-1) 309 | ``` 310 | 311 | 312 | ```python 313 | np.sqrt(-1) == np.emath.sqrt(-1) 314 | ``` 315 | #### 33. How to get the dates of yesterday, today and tomorrow? (★☆☆) 316 | 317 | 318 | ```python 319 | yesterday = np.datetime64('today') - np.timedelta64(1) 320 | today = np.datetime64('today') 321 | tomorrow = np.datetime64('today') + np.timedelta64(1) 322 | ``` 323 | #### 34. How to get all the dates corresponding to the month of July 2016? (★★☆) 324 | 325 | 326 | ```python 327 | Z = np.arange('2016-07', '2016-08', dtype='datetime64[D]') 328 | print(Z) 329 | ``` 330 | #### 35. How to compute ((A+B)*(-A/2)) in place (without copy)? (★★☆) 331 | 332 | 333 | ```python 334 | A = np.ones(3)*1 335 | B = np.ones(3)*2 336 | np.add(A,B,out=B) 337 | np.divide(A,2,out=A) 338 | np.negative(A,out=A) 339 | np.multiply(A,B,out=A) 340 | ``` 341 | #### 36. Extract the integer part of a random array of positive numbers using 4 different methods (★★☆) 342 | 343 | 344 | ```python 345 | Z = np.random.uniform(0,10,10) 346 | 347 | print(Z - Z%1) 348 | print(Z // 1) 349 | print(np.floor(Z)) 350 | print(Z.astype(int)) 351 | print(np.trunc(Z)) 352 | ``` 353 | #### 37. Create a 5x5 matrix with row values ranging from 0 to 4 (★★☆) 354 | 355 | 356 | ```python 357 | Z = np.zeros((5,5)) 358 | Z += np.arange(5) 359 | print(Z) 360 | 361 | # without broadcasting 362 | Z = np.tile(np.arange(0, 5), (5,1)) 363 | print(Z) 364 | ``` 365 | #### 38. Consider a generator function that generates 10 integers and use it to build an array (★☆☆) 366 | 367 | 368 | ```python 369 | def generate(): 370 | for x in range(10): 371 | yield x 372 | Z = np.fromiter(generate(),dtype=float,count=-1) 373 | print(Z) 374 | ``` 375 | #### 39. Create a vector of size 10 with values ranging from 0 to 1, both excluded (★★☆) 376 | 377 | 378 | ```python 379 | Z = np.linspace(0,1,11,endpoint=False)[1:] 380 | print(Z) 381 | ``` 382 | #### 40. Create a random vector of size 10 and sort it (★★☆) 383 | 384 | 385 | ```python 386 | Z = np.random.random(10) 387 | Z.sort() 388 | print(Z) 389 | ``` 390 | #### 41. How to sum a small array faster than np.sum? (★★☆) 391 | 392 | 393 | ```python 394 | # Author: Evgeni Burovski 395 | 396 | Z = np.arange(10) 397 | np.add.reduce(Z) 398 | ``` 399 | #### 42. Consider two random arrays A and B, check if they are equal (★★☆) 400 | 401 | 402 | ```python 403 | A = np.random.randint(0,2,5) 404 | B = np.random.randint(0,2,5) 405 | 406 | # Assuming identical shape of the arrays and a tolerance for the comparison of values 407 | equal = np.allclose(A,B) 408 | print(equal) 409 | 410 | # Checking both the shape and the element values, no tolerance (values have to be exactly equal) 411 | equal = np.array_equal(A,B) 412 | print(equal) 413 | ``` 414 | #### 43. Make an array immutable (read-only) (★★☆) 415 | 416 | 417 | ```python 418 | Z = np.zeros(10) 419 | Z.flags.writeable = False 420 | Z[0] = 1 421 | ``` 422 | #### 44. Consider a random 10x2 matrix representing cartesian coordinates, convert them to polar coordinates (★★☆) 423 | 424 | 425 | ```python 426 | Z = np.random.random((10,2)) 427 | X,Y = Z[:,0], Z[:,1] 428 | R = np.sqrt(X**2+Y**2) 429 | T = np.arctan2(Y,X) 430 | print(R) 431 | print(T) 432 | ``` 433 | #### 45. Create random vector of size 10 and replace the maximum value by 0 (★★☆) 434 | 435 | 436 | ```python 437 | Z = np.random.random(10) 438 | Z[Z.argmax()] = 0 439 | print(Z) 440 | ``` 441 | #### 46. Create a structured array with `x` and `y` coordinates covering the [0,1]x[0,1] area (★★☆) 442 | 443 | 444 | ```python 445 | Z = np.zeros((5,5), [('x',float),('y',float)]) 446 | Z['x'], Z['y'] = np.meshgrid(np.linspace(0,1,5), 447 | np.linspace(0,1,5)) 448 | print(Z) 449 | ``` 450 | #### 47. Given two arrays, X and Y, construct the Cauchy matrix C (Cij =1/(xi - yj)) (★★☆) 451 | 452 | 453 | ```python 454 | # Author: Evgeni Burovski 455 | 456 | X = np.arange(8) 457 | Y = X + 0.5 458 | C = 1.0 / np.subtract.outer(X, Y) 459 | print(np.linalg.det(C)) 460 | ``` 461 | #### 48. Print the minimum and maximum representable values for each numpy scalar type (★★☆) 462 | 463 | 464 | ```python 465 | for dtype in [np.int8, np.int32, np.int64]: 466 | print(np.iinfo(dtype).min) 467 | print(np.iinfo(dtype).max) 468 | for dtype in [np.float32, np.float64]: 469 | print(np.finfo(dtype).min) 470 | print(np.finfo(dtype).max) 471 | print(np.finfo(dtype).eps) 472 | ``` 473 | #### 49. How to print all the values of an array? (★★☆) 474 | 475 | 476 | ```python 477 | np.set_printoptions(threshold=float("inf")) 478 | Z = np.zeros((40,40)) 479 | print(Z) 480 | ``` 481 | #### 50. How to find the closest value (to a given scalar) in a vector? (★★☆) 482 | 483 | 484 | ```python 485 | Z = np.arange(100) 486 | v = np.random.uniform(0,100) 487 | index = (np.abs(Z-v)).argmin() 488 | print(Z[index]) 489 | ``` 490 | #### 51. Create a structured array representing a position (x,y) and a color (r,g,b) (★★☆) 491 | 492 | 493 | ```python 494 | Z = np.zeros(10, [ ('position', [ ('x', float, 1), 495 | ('y', float, 1)]), 496 | ('color', [ ('r', float, 1), 497 | ('g', float, 1), 498 | ('b', float, 1)])]) 499 | print(Z) 500 | ``` 501 | #### 52. Consider a random vector with shape (100,2) representing coordinates, find point by point distances (★★☆) 502 | 503 | 504 | ```python 505 | Z = np.random.random((10,2)) 506 | X,Y = np.atleast_2d(Z[:,0], Z[:,1]) 507 | D = np.sqrt( (X-X.T)**2 + (Y-Y.T)**2) 508 | print(D) 509 | 510 | # Much faster with scipy 511 | import scipy 512 | # Thanks Gavin Heverly-Coulson (#issue 1) 513 | import scipy.spatial 514 | 515 | Z = np.random.random((10,2)) 516 | D = scipy.spatial.distance.cdist(Z,Z) 517 | print(D) 518 | ``` 519 | #### 53. How to convert a float (32 bits) array into an integer (32 bits) array in place? 520 | 521 | 522 | ```python 523 | # Thanks Vikas (https://stackoverflow.com/a/10622758/5989906) 524 | # & unutbu (https://stackoverflow.com/a/4396247/5989906) 525 | Z = (np.random.rand(10)*100).astype(np.float32) 526 | Y = Z.view(np.int32) 527 | Y[:] = Z 528 | print(Y) 529 | ``` 530 | #### 54. How to read the following file? (★★☆) 531 | ``` 532 | 1, 2, 3, 4, 5 533 | 6, , , 7, 8 534 | , , 9,10,11 535 | ``` 536 | 537 | 538 | ```python 539 | from io import StringIO 540 | 541 | # Fake file 542 | s = StringIO('''1, 2, 3, 4, 5 543 | 544 | 6, , , 7, 8 545 | 546 | , , 9,10,11 547 | ''') 548 | Z = np.genfromtxt(s, delimiter=",", dtype=np.int) 549 | print(Z) 550 | ``` 551 | #### 55. What is the equivalent of enumerate for numpy arrays? (★★☆) 552 | 553 | 554 | ```python 555 | Z = np.arange(9).reshape(3,3) 556 | for index, value in np.ndenumerate(Z): 557 | print(index, value) 558 | for index in np.ndindex(Z.shape): 559 | print(index, Z[index]) 560 | ``` 561 | #### 56. Generate a generic 2D Gaussian-like array (★★☆) 562 | 563 | 564 | ```python 565 | X, Y = np.meshgrid(np.linspace(-1,1,10), np.linspace(-1,1,10)) 566 | D = np.sqrt(X*X+Y*Y) 567 | sigma, mu = 1.0, 0.0 568 | G = np.exp(-( (D-mu)**2 / ( 2.0 * sigma**2 ) ) ) 569 | print(G) 570 | ``` 571 | #### 57. How to randomly place p elements in a 2D array? (★★☆) 572 | 573 | 574 | ```python 575 | # Author: Divakar 576 | 577 | n = 10 578 | p = 3 579 | Z = np.zeros((n,n)) 580 | np.put(Z, np.random.choice(range(n*n), p, replace=False),1) 581 | print(Z) 582 | ``` 583 | #### 58. Subtract the mean of each row of a matrix (★★☆) 584 | 585 | 586 | ```python 587 | # Author: Warren Weckesser 588 | 589 | X = np.random.rand(5, 10) 590 | 591 | # Recent versions of numpy 592 | Y = X - X.mean(axis=1, keepdims=True) 593 | 594 | # Older versions of numpy 595 | Y = X - X.mean(axis=1).reshape(-1, 1) 596 | 597 | print(Y) 598 | ``` 599 | #### 59. How to sort an array by the nth column? (★★☆) 600 | 601 | 602 | ```python 603 | # Author: Steve Tjoa 604 | 605 | Z = np.random.randint(0,10,(3,3)) 606 | print(Z) 607 | print(Z[Z[:,1].argsort()]) 608 | ``` 609 | #### 60. How to tell if a given 2D array has null columns? (★★☆) 610 | 611 | 612 | ```python 613 | # Author: Warren Weckesser 614 | 615 | # null : 0 616 | Z = np.random.randint(0,3,(3,10)) 617 | print((~Z.any(axis=0)).any()) 618 | 619 | # null : np.nan 620 | Z=np.array([ 621 | [0,1,np.nan], 622 | [1,2,np.nan], 623 | [4,5,np.nan] 624 | ]) 625 | print(np.isnan(Z).all(axis=0)) 626 | ``` 627 | #### 61. Find the nearest value from a given value in an array (★★☆) 628 | 629 | 630 | ```python 631 | Z = np.random.uniform(0,1,10) 632 | z = 0.5 633 | m = Z.flat[np.abs(Z - z).argmin()] 634 | print(m) 635 | ``` 636 | #### 62. Considering two arrays with shape (1,3) and (3,1), how to compute their sum using an iterator? (★★☆) 637 | 638 | 639 | ```python 640 | A = np.arange(3).reshape(3,1) 641 | B = np.arange(3).reshape(1,3) 642 | it = np.nditer([A,B,None]) 643 | for x,y,z in it: z[...] = x + y 644 | print(it.operands[2]) 645 | ``` 646 | #### 63. Create an array class that has a name attribute (★★☆) 647 | 648 | 649 | ```python 650 | class NamedArray(np.ndarray): 651 | def __new__(cls, array, name="no name"): 652 | obj = np.asarray(array).view(cls) 653 | obj.name = name 654 | return obj 655 | def __array_finalize__(self, obj): 656 | if obj is None: return 657 | self.name = getattr(obj, 'name', "no name") 658 | 659 | Z = NamedArray(np.arange(10), "range_10") 660 | print (Z.name) 661 | ``` 662 | #### 64. Consider a given vector, how to add 1 to each element indexed by a second vector (be careful with repeated indices)? (★★★) 663 | 664 | 665 | ```python 666 | # Author: Brett Olsen 667 | 668 | Z = np.ones(10) 669 | I = np.random.randint(0,len(Z),20) 670 | Z += np.bincount(I, minlength=len(Z)) 671 | print(Z) 672 | 673 | # Another solution 674 | # Author: Bartosz Telenczuk 675 | np.add.at(Z, I, 1) 676 | print(Z) 677 | ``` 678 | #### 65. How to accumulate elements of a vector (X) to an array (F) based on an index list (I)? (★★★) 679 | 680 | 681 | ```python 682 | # Author: Alan G Isaac 683 | 684 | X = [1,2,3,4,5,6] 685 | I = [1,3,9,3,4,1] 686 | F = np.bincount(I,X) 687 | print(F) 688 | ``` 689 | #### 66. Considering a (w,h,3) image of (dtype=ubyte), compute the number of unique colors (★★☆) 690 | 691 | 692 | ```python 693 | # Author: Fisher Wang 694 | 695 | w, h = 256, 256 696 | I = np.random.randint(0, 4, (h, w, 3)).astype(np.ubyte) 697 | colors = np.unique(I.reshape(-1, 3), axis=0) 698 | n = len(colors) 699 | print(n) 700 | 701 | # Faster version 702 | # Author: Mark Setchell 703 | # https://stackoverflow.com/a/59671950/2836621 704 | 705 | w, h = 256, 256 706 | I = np.random.randint(0,4,(h,w,3), dtype=np.uint8) 707 | 708 | # View each pixel as a single 24-bit integer, rather than three 8-bit bytes 709 | I24 = np.dot(I.astype(np.uint32),[1,256,65536]) 710 | 711 | # Count unique colours 712 | n = len(np.unique(I24)) 713 | print(n) 714 | ``` 715 | #### 67. Considering a four dimensions array, how to get sum over the last two axis at once? (★★★) 716 | 717 | 718 | ```python 719 | A = np.random.randint(0,10,(3,4,3,4)) 720 | # solution by passing a tuple of axes (introduced in numpy 1.7.0) 721 | sum = A.sum(axis=(-2,-1)) 722 | print(sum) 723 | # solution by flattening the last two dimensions into one 724 | # (useful for functions that don't accept tuples for axis argument) 725 | sum = A.reshape(A.shape[:-2] + (-1,)).sum(axis=-1) 726 | print(sum) 727 | ``` 728 | #### 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? (★★★) 729 | 730 | 731 | ```python 732 | # Author: Jaime Fernández del Río 733 | 734 | D = np.random.uniform(0,1,100) 735 | S = np.random.randint(0,10,100) 736 | D_sums = np.bincount(S, weights=D) 737 | D_counts = np.bincount(S) 738 | D_means = D_sums / D_counts 739 | print(D_means) 740 | 741 | # Pandas solution as a reference due to more intuitive code 742 | import pandas as pd 743 | print(pd.Series(D).groupby(S).mean()) 744 | ``` 745 | #### 69. How to get the diagonal of a dot product? (★★★) 746 | 747 | 748 | ```python 749 | # Author: Mathieu Blondel 750 | 751 | A = np.random.uniform(0,1,(5,5)) 752 | B = np.random.uniform(0,1,(5,5)) 753 | 754 | # Slow version 755 | np.diag(np.dot(A, B)) 756 | 757 | # Fast version 758 | np.sum(A * B.T, axis=1) 759 | 760 | # Faster version 761 | np.einsum("ij,ji->i", A, B) 762 | ``` 763 | #### 70. Consider the vector [1, 2, 3, 4, 5], how to build a new vector with 3 consecutive zeros interleaved between each value? (★★★) 764 | 765 | 766 | ```python 767 | # Author: Warren Weckesser 768 | 769 | Z = np.array([1,2,3,4,5]) 770 | nz = 3 771 | Z0 = np.zeros(len(Z) + (len(Z)-1)*(nz)) 772 | Z0[::nz+1] = Z 773 | print(Z0) 774 | ``` 775 | #### 71. Consider an array of dimension (5,5,3), how to multiply it by an array with dimensions (5,5)? (★★★) 776 | 777 | 778 | ```python 779 | A = np.ones((5,5,3)) 780 | B = 2*np.ones((5,5)) 781 | print(A * B[:,:,None]) 782 | ``` 783 | #### 72. How to swap two rows of an array? (★★★) 784 | 785 | 786 | ```python 787 | # Author: Eelco Hoogendoorn 788 | 789 | A = np.arange(25).reshape(5,5) 790 | A[[0,1]] = A[[1,0]] 791 | print(A) 792 | ``` 793 | #### 73. Consider a set of 10 triplets describing 10 triangles (with shared vertices), find the set of unique line segments composing all the triangles (★★★) 794 | 795 | 796 | ```python 797 | # Author: Nicolas P. Rougier 798 | 799 | faces = np.random.randint(0,100,(10,3)) 800 | F = np.roll(faces.repeat(2,axis=1),-1,axis=1) 801 | F = F.reshape(len(F)*3,2) 802 | F = np.sort(F,axis=1) 803 | G = F.view( dtype=[('p0',F.dtype),('p1',F.dtype)] ) 804 | G = np.unique(G) 805 | print(G) 806 | ``` 807 | #### 74. Given a sorted array C that corresponds to a bincount, how to produce an array A such that np.bincount(A) == C? (★★★) 808 | 809 | 810 | ```python 811 | # Author: Jaime Fernández del Río 812 | 813 | C = np.bincount([1,1,2,3,4,4,6]) 814 | A = np.repeat(np.arange(len(C)), C) 815 | print(A) 816 | ``` 817 | #### 75. How to compute averages using a sliding window over an array? (★★★) 818 | 819 | 820 | ```python 821 | # Author: Jaime Fernández del Río 822 | 823 | def moving_average(a, n=3) : 824 | ret = np.cumsum(a, dtype=float) 825 | ret[n:] = ret[n:] - ret[:-n] 826 | return ret[n - 1:] / n 827 | Z = np.arange(20) 828 | print(moving_average(Z, n=3)) 829 | 830 | # Author: Jeff Luo (@Jeff1999) 831 | # make sure your NumPy >= 1.20.0 832 | 833 | from numpy.lib.stride_tricks import sliding_window_view 834 | 835 | Z = np.arange(20) 836 | print(sliding_window_view(Z, window_shape=3).mean(axis=-1)) 837 | ``` 838 | #### 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]) (★★★) 839 | 840 | 841 | ```python 842 | # Author: Joe Kington / Erik Rigtorp 843 | from numpy.lib import stride_tricks 844 | 845 | def rolling(a, window): 846 | shape = (a.size - window + 1, window) 847 | strides = (a.strides[0], a.strides[0]) 848 | return stride_tricks.as_strided(a, shape=shape, strides=strides) 849 | Z = rolling(np.arange(10), 3) 850 | print(Z) 851 | 852 | # Author: Jeff Luo (@Jeff1999) 853 | 854 | Z = np.arange(10) 855 | print(sliding_window_view(Z, window_shape=3)) 856 | ``` 857 | #### 77. How to negate a boolean, or to change the sign of a float inplace? (★★★) 858 | 859 | 860 | ```python 861 | # Author: Nathaniel J. Smith 862 | 863 | Z = np.random.randint(0,2,100) 864 | np.logical_not(Z, out=Z) 865 | 866 | Z = np.random.uniform(-1.0,1.0,100) 867 | np.negative(Z, out=Z) 868 | ``` 869 | #### 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])? (★★★) 870 | 871 | 872 | ```python 873 | def distance(P0, P1, p): 874 | T = P1 - P0 875 | L = (T**2).sum(axis=1) 876 | U = -((P0[:,0]-p[...,0])*T[:,0] + (P0[:,1]-p[...,1])*T[:,1]) / L 877 | U = U.reshape(len(U),1) 878 | D = P0 + U*T - p 879 | return np.sqrt((D**2).sum(axis=1)) 880 | 881 | P0 = np.random.uniform(-10,10,(10,2)) 882 | P1 = np.random.uniform(-10,10,(10,2)) 883 | p = np.random.uniform(-10,10,( 1,2)) 884 | print(distance(P0, P1, p)) 885 | ``` 886 | #### 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])? (★★★) 887 | 888 | 889 | ```python 890 | # Author: Italmassov Kuanysh 891 | 892 | # based on distance function from previous question 893 | P0 = np.random.uniform(-10, 10, (10,2)) 894 | P1 = np.random.uniform(-10,10,(10,2)) 895 | p = np.random.uniform(-10, 10, (10,2)) 896 | print(np.array([distance(P0,P1,p_i) for p_i in p])) 897 | 898 | # Author: Yang Wu (Broadcasting) 899 | def distance_points_to_lines(p: np.ndarray, p_1: np.ndarray, p_2: np.ndarray) -> np.ndarray: 900 | x_0, y_0 = p.T # Shape -> (n points, ) 901 | x_1, y_1 = p_1.T # Shape -> (n lines, ) 902 | x_2, y_2 = p_2.T # Shape -> (n lines, ) 903 | 904 | # Displacement vector coordinates from p_1 -> p_2 905 | dx = x_2 - x_1 # Shape -> (n lines, ) 906 | dy = y_2 - y_1 # Shape -> (n lines, ) 907 | 908 | # The 'cross product' term 909 | cross_term = x_2 * y_1 - y_2 * x_1 # Shape -> (n lines, ) 910 | 911 | # Broadcast x_0, y_0 (n points, 1) and dx, dy, cross_term (1, n lines) -> (n points, n lines) 912 | numerator = np.abs( 913 | dy[np.newaxis, :] * x_0[:, np.newaxis] 914 | - dx[np.newaxis, :] * y_0[:, np.newaxis] 915 | + cross_term[np.newaxis, :] 916 | ) 917 | denominator = np.sqrt(dx**2 + dy**2) # Shape -> (n lines, ) 918 | 919 | # Shape (n points, n lines) / (1, n_lines) -> (n points, n lines) 920 | return numerator / denominator[np.newaxis, :] 921 | 922 | distance_points_to_lines(p, P0, P1) 923 | ``` 924 | #### 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) (★★★) 925 | 926 | 927 | ```python 928 | # Author: Nicolas Rougier 929 | 930 | Z = np.random.randint(0,10,(10,10)) 931 | shape = (5,5) 932 | fill = 0 933 | position = (1,1) 934 | 935 | R = np.ones(shape, dtype=Z.dtype)*fill 936 | P = np.array(list(position)).astype(int) 937 | Rs = np.array(list(R.shape)).astype(int) 938 | Zs = np.array(list(Z.shape)).astype(int) 939 | 940 | R_start = np.zeros((len(shape),)).astype(int) 941 | R_stop = np.array(list(shape)).astype(int) 942 | Z_start = (P-Rs//2) 943 | Z_stop = (P+Rs//2)+Rs%2 944 | 945 | R_start = (R_start - np.minimum(Z_start,0)).tolist() 946 | Z_start = (np.maximum(Z_start,0)).tolist() 947 | R_stop = np.maximum(R_start, (R_stop - np.maximum(Z_stop-Zs,0))).tolist() 948 | Z_stop = (np.minimum(Z_stop,Zs)).tolist() 949 | 950 | r = [slice(start,stop) for start,stop in zip(R_start,R_stop)] 951 | z = [slice(start,stop) for start,stop in zip(Z_start,Z_stop)] 952 | R[r] = Z[z] 953 | print(Z) 954 | print(R) 955 | ``` 956 | #### 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]]? (★★★) 957 | 958 | 959 | ```python 960 | # Author: Stefan van der Walt 961 | 962 | Z = np.arange(1,15,dtype=np.uint32) 963 | R = stride_tricks.as_strided(Z,(11,4),(4,4)) 964 | print(R) 965 | 966 | # Author: Jeff Luo (@Jeff1999) 967 | 968 | Z = np.arange(1, 15, dtype=np.uint32) 969 | print(sliding_window_view(Z, window_shape=4)) 970 | ``` 971 | #### 82. Compute a matrix rank (★★★) 972 | 973 | 974 | ```python 975 | # Author: Stefan van der Walt 976 | 977 | Z = np.random.uniform(0,1,(10,10)) 978 | U, S, V = np.linalg.svd(Z) # Singular Value Decomposition 979 | rank = np.sum(S > 1e-10) 980 | print(rank) 981 | 982 | # alternative solution: 983 | # Author: Jeff Luo (@Jeff1999) 984 | 985 | rank = np.linalg.matrix_rank(Z) 986 | print(rank) 987 | ``` 988 | #### 83. How to find the most frequent value in an array? 989 | 990 | 991 | ```python 992 | Z = np.random.randint(0,10,50) 993 | print(np.bincount(Z).argmax()) 994 | ``` 995 | #### 84. Extract all the contiguous 3x3 blocks from a random 10x10 matrix (★★★) 996 | 997 | 998 | ```python 999 | # Author: Chris Barker 1000 | 1001 | Z = np.random.randint(0,5,(10,10)) 1002 | n = 3 1003 | i = 1 + (Z.shape[0]-3) 1004 | j = 1 + (Z.shape[1]-3) 1005 | C = stride_tricks.as_strided(Z, shape=(i, j, n, n), strides=Z.strides + Z.strides) 1006 | print(C) 1007 | 1008 | # Author: Jeff Luo (@Jeff1999) 1009 | 1010 | Z = np.random.randint(0,5,(10,10)) 1011 | print(sliding_window_view(Z, window_shape=(3, 3))) 1012 | ``` 1013 | #### 85. Create a 2D array subclass such that Z[i,j] == Z[j,i] (★★★) 1014 | 1015 | 1016 | ```python 1017 | # Author: Eric O. Lebigot 1018 | # Note: only works for 2d array and value setting using indices 1019 | 1020 | class Symetric(np.ndarray): 1021 | def __setitem__(self, index, value): 1022 | i,j = index 1023 | super(Symetric, self).__setitem__((i,j), value) 1024 | super(Symetric, self).__setitem__((j,i), value) 1025 | 1026 | def symetric(Z): 1027 | return np.asarray(Z + Z.T - np.diag(Z.diagonal())).view(Symetric) 1028 | 1029 | S = symetric(np.random.randint(0,10,(5,5))) 1030 | S[2,3] = 42 1031 | print(S) 1032 | ``` 1033 | #### 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)) (★★★) 1034 | 1035 | 1036 | ```python 1037 | # Author: Stefan van der Walt 1038 | 1039 | p, n = 10, 20 1040 | M = np.ones((p,n,n)) 1041 | V = np.ones((p,n,1)) 1042 | S = np.tensordot(M, V, axes=[[0, 2], [0, 1]]) 1043 | print(S) 1044 | 1045 | # It works, because: 1046 | # M is (p,n,n) 1047 | # V is (p,n,1) 1048 | # Thus, summing over the paired axes 0 and 0 (of M and V independently), 1049 | # and 2 and 1, to remain with a (n,1) vector. 1050 | ``` 1051 | #### 87. Consider a 16x16 array, how to get the block-sum (block size is 4x4)? (★★★) 1052 | 1053 | 1054 | ```python 1055 | # Author: Robert Kern 1056 | 1057 | Z = np.ones((16,16)) 1058 | k = 4 1059 | S = np.add.reduceat(np.add.reduceat(Z, np.arange(0, Z.shape[0], k), axis=0), 1060 | np.arange(0, Z.shape[1], k), axis=1) 1061 | print(S) 1062 | 1063 | # alternative solution: 1064 | # Author: Sebastian Wallkötter (@FirefoxMetzger) 1065 | 1066 | Z = np.ones((16,16)) 1067 | k = 4 1068 | 1069 | windows = np.lib.stride_tricks.sliding_window_view(Z, (k, k)) 1070 | S = windows[::k, ::k, ...].sum(axis=(-2, -1)) 1071 | 1072 | # Author: Jeff Luo (@Jeff1999) 1073 | 1074 | Z = np.ones((16, 16)) 1075 | k = 4 1076 | print(sliding_window_view(Z, window_shape=(k, k))[::k, ::k].sum(axis=(-2, -1))) 1077 | ``` 1078 | #### 88. How to implement the Game of Life using numpy arrays? (★★★) 1079 | 1080 | 1081 | ```python 1082 | # Author: Nicolas Rougier 1083 | 1084 | def iterate(Z): 1085 | # Count neighbours 1086 | N = (Z[0:-2,0:-2] + Z[0:-2,1:-1] + Z[0:-2,2:] + 1087 | Z[1:-1,0:-2] + Z[1:-1,2:] + 1088 | Z[2: ,0:-2] + Z[2: ,1:-1] + Z[2: ,2:]) 1089 | 1090 | # Apply rules 1091 | birth = (N==3) & (Z[1:-1,1:-1]==0) 1092 | survive = ((N==2) | (N==3)) & (Z[1:-1,1:-1]==1) 1093 | Z[...] = 0 1094 | Z[1:-1,1:-1][birth | survive] = 1 1095 | return Z 1096 | 1097 | Z = np.random.randint(0,2,(50,50)) 1098 | for i in range(100): Z = iterate(Z) 1099 | print(Z) 1100 | ``` 1101 | #### 89. How to get the n largest values of an array (★★★) 1102 | 1103 | 1104 | ```python 1105 | Z = np.arange(10000) 1106 | np.random.shuffle(Z) 1107 | n = 5 1108 | 1109 | # Slow 1110 | print (Z[np.argsort(Z)[-n:]]) 1111 | 1112 | # Fast 1113 | print (Z[np.argpartition(-Z,n)[:n]]) 1114 | ``` 1115 | #### 90. Given an arbitrary number of vectors, build the cartesian product (every combination of every item) (★★★) 1116 | 1117 | 1118 | ```python 1119 | # Author: Stefan Van der Walt 1120 | 1121 | def cartesian(arrays): 1122 | arrays = [np.asarray(a) for a in arrays] 1123 | shape = (len(x) for x in arrays) 1124 | 1125 | ix = np.indices(shape, dtype=int) 1126 | ix = ix.reshape(len(arrays), -1).T 1127 | 1128 | for n, arr in enumerate(arrays): 1129 | ix[:, n] = arrays[n][ix[:, n]] 1130 | 1131 | return ix 1132 | 1133 | print (cartesian(([1, 2, 3], [4, 5], [6, 7]))) 1134 | ``` 1135 | #### 91. How to create a record array from a regular array? (★★★) 1136 | 1137 | 1138 | ```python 1139 | Z = np.array([("Hello", 2.5, 3), 1140 | ("World", 3.6, 2)]) 1141 | R = np.core.records.fromarrays(Z.T, 1142 | names='col1, col2, col3', 1143 | formats = 'S8, f8, i8') 1144 | print(R) 1145 | ``` 1146 | #### 92. Consider a large vector Z, compute Z to the power of 3 using 3 different methods (★★★) 1147 | 1148 | 1149 | ```python 1150 | # Author: Ryan G. 1151 | 1152 | x = np.random.rand(int(5e7)) 1153 | 1154 | %timeit np.power(x,3) 1155 | %timeit x*x*x 1156 | %timeit np.einsum('i,i,i->i',x,x,x) 1157 | ``` 1158 | #### 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? (★★★) 1159 | 1160 | 1161 | ```python 1162 | # Author: Gabe Schwartz 1163 | 1164 | A = np.random.randint(0,5,(8,3)) 1165 | B = np.random.randint(0,5,(2,2)) 1166 | 1167 | C = (A[..., np.newaxis, np.newaxis] == B) 1168 | rows = np.where(C.any((3,1)).all(1))[0] 1169 | print(rows) 1170 | ``` 1171 | #### 94. Considering a 10x3 matrix, extract rows with unequal values (e.g. [2,2,3]) (★★★) 1172 | 1173 | 1174 | ```python 1175 | # Author: Robert Kern 1176 | 1177 | Z = np.random.randint(0,5,(10,3)) 1178 | print(Z) 1179 | # solution for arrays of all dtypes (including string arrays and record arrays) 1180 | E = np.all(Z[:,1:] == Z[:,:-1], axis=1) 1181 | U = Z[~E] 1182 | print(U) 1183 | # soluiton for numerical arrays only, will work for any number of columns in Z 1184 | U = Z[Z.max(axis=1) != Z.min(axis=1),:] 1185 | print(U) 1186 | ``` 1187 | #### 95. Convert a vector of ints into a matrix binary representation (★★★) 1188 | 1189 | 1190 | ```python 1191 | # Author: Warren Weckesser 1192 | 1193 | I = np.array([0, 1, 2, 3, 15, 16, 32, 64, 128]) 1194 | B = ((I.reshape(-1,1) & (2**np.arange(8))) != 0).astype(int) 1195 | print(B[:,::-1]) 1196 | 1197 | # Author: Daniel T. McDonald 1198 | 1199 | I = np.array([0, 1, 2, 3, 15, 16, 32, 64, 128], dtype=np.uint8) 1200 | print(np.unpackbits(I[:, np.newaxis], axis=1)) 1201 | ``` 1202 | #### 96. Given a two dimensional array, how to extract unique rows? (★★★) 1203 | 1204 | 1205 | ```python 1206 | # Author: Jaime Fernández del Río 1207 | 1208 | Z = np.random.randint(0,2,(6,3)) 1209 | T = np.ascontiguousarray(Z).view(np.dtype((np.void, Z.dtype.itemsize * Z.shape[1]))) 1210 | _, idx = np.unique(T, return_index=True) 1211 | uZ = Z[idx] 1212 | print(uZ) 1213 | 1214 | # Author: Andreas Kouzelis 1215 | # NumPy >= 1.13 1216 | uZ = np.unique(Z, axis=0) 1217 | print(uZ) 1218 | ``` 1219 | #### 97. Considering 2 vectors A & B, write the einsum equivalent of inner, outer, sum, and mul function (★★★) 1220 | 1221 | 1222 | ```python 1223 | # Author: Alex Riley 1224 | # Make sure to read: http://ajcr.net/Basic-guide-to-einsum/ 1225 | 1226 | A = np.random.uniform(0,1,10) 1227 | B = np.random.uniform(0,1,10) 1228 | 1229 | np.einsum('i->', A) # np.sum(A) 1230 | np.einsum('i,i->i', A, B) # A * B 1231 | np.einsum('i,i', A, B) # np.inner(A, B) 1232 | np.einsum('i,j->ij', A, B) # np.outer(A, B) 1233 | ``` 1234 | #### 98. Considering a path described by two vectors (X,Y), how to sample it using equidistant samples (★★★)? 1235 | 1236 | 1237 | ```python 1238 | # Author: Bas Swinckels 1239 | 1240 | phi = np.arange(0, 10*np.pi, 0.1) 1241 | a = 1 1242 | x = a*phi*np.cos(phi) 1243 | y = a*phi*np.sin(phi) 1244 | 1245 | dr = (np.diff(x)**2 + np.diff(y)**2)**.5 # segment lengths 1246 | r = np.zeros_like(x) 1247 | r[1:] = np.cumsum(dr) # integrate path 1248 | r_int = np.linspace(0, r.max(), 200) # regular spaced path 1249 | x_int = np.interp(r_int, r, x) # integrate path 1250 | y_int = np.interp(r_int, r, y) 1251 | ``` 1252 | #### 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. (★★★) 1253 | 1254 | 1255 | ```python 1256 | # Author: Evgeni Burovski 1257 | 1258 | X = np.asarray([[1.0, 0.0, 3.0, 8.0], 1259 | [2.0, 0.0, 1.0, 1.0], 1260 | [1.5, 2.5, 1.0, 0.0]]) 1261 | n = 4 1262 | M = np.logical_and.reduce(np.mod(X, 1) == 0, axis=-1) 1263 | M &= (X.sum(axis=-1) == n) 1264 | print(X[M]) 1265 | ``` 1266 | #### 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). (★★★) 1267 | 1268 | 1269 | ```python 1270 | # Author: Jessica B. Hamrick 1271 | 1272 | X = np.random.randn(100) # random 1D array 1273 | N = 1000 # number of bootstrap samples 1274 | idx = np.random.randint(0, X.size, (N, X.size)) 1275 | means = X[idx].mean(axis=1) 1276 | confint = np.percentile(means, [2.5, 97.5]) 1277 | print(confint) 1278 | ``` -------------------------------------------------------------------------------- /100_Numpy_random.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "ea6cbc4b", 6 | "metadata": {}, 7 | "source": [ 8 | "# 100 numpy exercises\n", 9 | "\n", 10 | "This is a collection of exercises that have been collected in the numpy mailing list, on stack overflow\n", 11 | "and in the numpy documentation. The goal of this collection is to offer a quick reference for both old\n", 12 | "and new users but also to provide a set of exercises for those who teach.\n", 13 | "\n", 14 | "\n", 15 | "If you find an error or think you've a better way to solve some of them, feel\n", 16 | "free to open an issue at ." 17 | ] 18 | }, 19 | { 20 | "cell_type": "markdown", 21 | "id": "354a533b", 22 | "metadata": {}, 23 | "source": [ 24 | "File automatically generated. See the documentation to update questions/answers/hints programmatically." 25 | ] 26 | }, 27 | { 28 | "cell_type": "markdown", 29 | "id": "9efa41bf", 30 | "metadata": {}, 31 | "source": [ 32 | "Run the `initialize.py` module, then call a random question with `pick()` an hint towards its solution with\n", 33 | "`hint(n)` and the answer with `answer(n)`, where n is the number of the picked question." 34 | ] 35 | }, 36 | { 37 | "cell_type": "code", 38 | "execution_count": null, 39 | "id": "1a6e8fdb", 40 | "metadata": {}, 41 | "outputs": [], 42 | "source": [ 43 | "%run initialise.py" 44 | ] 45 | }, 46 | { 47 | "cell_type": "code", 48 | "execution_count": null, 49 | "id": "d1e7d785", 50 | "metadata": {}, 51 | "outputs": [], 52 | "source": [ 53 | "pick()" 54 | ] 55 | } 56 | ], 57 | "metadata": {}, 58 | "nbformat": 4, 59 | "nbformat_minor": 5 60 | } 61 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2016 Nicolas P. Rougier 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## 100 numpy exercises 2 | 3 | [![Binder](http://mybinder.org/badge.svg)](http://mybinder.org:/repo/rougier/numpy-100/notebooks/100%20Numpy%20exercises.ipynb) 4 | 5 | This 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/). 6 | 7 | → [Test them on Binder](http://mybinder.org:/repo/rougier/numpy-100/notebooks/100_Numpy_exercises.ipynb) 8 | → [Read them on GitHub](100_Numpy_exercises.md) 9 | 10 | Note: markdown and ipython notebook are created programmatically from the source data in `source/exercises.ktx`. 11 | To modify the content of these files, please change the text in the source and run the `generators.py` module with a python 12 | interpreter with the libraries under `requirements.txt` installed. 13 | 14 | The keyed text format (`ktx`) is a minimal human readable key-values to store text (markdown or others) indexed by keys. 15 | 16 | This work is licensed under the MIT license. 17 | [![DOI](https://zenodo.org/badge/10173/rougier/numpy-100.svg)](https://zenodo.org/badge/latestdoi/10173/rougier/numpy-100) 18 | 19 | 20 | ### Variants in Other Languages 21 | 22 | - **Julia**: [100 Julia Exercises](https://github.com/RoyiAvital/Julia100Exercises). 23 | -------------------------------------------------------------------------------- /generators.py: -------------------------------------------------------------------------------- 1 | import os 2 | import nbformat as nbf 3 | import mdutils 4 | 5 | 6 | def ktx_to_dict(input_file, keystarter='<'): 7 | """ parsing keyed text to a python dictionary. """ 8 | answer = dict() 9 | 10 | with open(input_file, 'r+', encoding='utf-8') as f: 11 | lines = f.readlines() 12 | 13 | k, val = '', '' 14 | for line in lines: 15 | if line.startswith(keystarter): 16 | k = line.replace(keystarter, '').strip() 17 | val = '' 18 | else: 19 | val += line 20 | 21 | if k: 22 | answer.update({k: val.strip()}) 23 | 24 | return answer 25 | 26 | 27 | def dict_to_ktx(input_dict, output_file, keystarter='<'): 28 | """ Store a python dictionary to a keyed text""" 29 | with open(output_file, 'w+') as f: 30 | for k, val in input_dict.items(): 31 | f.write(f'{keystarter} {k}\n') 32 | f.write(f'{val}\n\n') 33 | 34 | 35 | HEADERS = ktx_to_dict(os.path.join('source', 'headers.ktx')) 36 | QHA = ktx_to_dict(os.path.join('source', 'exercises100.ktx')) 37 | 38 | 39 | def create_jupyter_notebook(destination_filename='100_Numpy_exercises.ipynb'): 40 | """ Programmatically create jupyter notebook with the questions (and hints and solutions if required) 41 | saved under source files """ 42 | 43 | # Create cells sequence 44 | nb = nbf.v4.new_notebook() 45 | 46 | nb['cells'] = [] 47 | 48 | # - Add header: 49 | nb['cells'].append(nbf.v4.new_markdown_cell(HEADERS["header"])) 50 | nb['cells'].append(nbf.v4.new_markdown_cell(HEADERS["sub_header"])) 51 | nb['cells'].append(nbf.v4.new_markdown_cell(HEADERS["jupyter_instruction"])) 52 | 53 | # - Add initialisation 54 | nb['cells'].append(nbf.v4.new_code_cell('%run initialise.py')) 55 | 56 | # - Add questions and empty spaces for answers 57 | for n in range(1, 101): 58 | nb['cells'].append(nbf.v4.new_markdown_cell(f'#### {n}. ' + QHA[f'q{n}'])) 59 | nb['cells'].append(nbf.v4.new_code_cell("")) 60 | 61 | # Delete file if one with the same name is found 62 | if os.path.exists(destination_filename): 63 | os.remove(destination_filename) 64 | 65 | # Write sequence to file 66 | nbf.write(nb, destination_filename) 67 | 68 | 69 | def create_jupyter_notebook_random_question(destination_filename='100_Numpy_random.ipynb'): 70 | """ Programmatically create jupyter notebook with the questions (and hints and solutions if required) 71 | saved under source files """ 72 | 73 | # Create cells sequence 74 | nb = nbf.v4.new_notebook() 75 | 76 | nb['cells'] = [] 77 | 78 | # - Add header: 79 | nb['cells'].append(nbf.v4.new_markdown_cell(HEADERS["header"])) 80 | nb['cells'].append(nbf.v4.new_markdown_cell(HEADERS["sub_header"])) 81 | nb['cells'].append(nbf.v4.new_markdown_cell(HEADERS["jupyter_instruction_rand"])) 82 | 83 | # - Add initialisation 84 | nb['cells'].append(nbf.v4.new_code_cell('%run initialise.py')) 85 | nb['cells'].append(nbf.v4.new_code_cell("pick()")) 86 | 87 | # Delete file if one with the same name is found 88 | if os.path.exists(destination_filename): 89 | os.remove(destination_filename) 90 | 91 | # Write sequence to file 92 | nbf.write(nb, destination_filename) 93 | 94 | 95 | def create_markdown(destination_filename='100_Numpy_exercises', with_hints=False, with_solutions=False): 96 | # Create file name 97 | if with_hints: 98 | destination_filename += '_with_hints' 99 | if with_solutions: 100 | destination_filename += '_with_solutions' 101 | 102 | # Initialise file 103 | mdfile = mdutils.MdUtils(file_name=destination_filename) 104 | 105 | # Add headers 106 | mdfile.write(HEADERS["header"] + '\n') 107 | mdfile.write(HEADERS["sub_header"] + '\n') 108 | 109 | # Add questions (and hint or answers if required) 110 | for n in range(1, 101): 111 | mdfile.new_header(title=f"{n}. {QHA[f'q{n}']}", level=4, add_table_of_contents="n") 112 | if with_hints: 113 | mdfile.write(f"`{QHA[f'h{n}']}`") 114 | if with_solutions: 115 | mdfile.insert_code(QHA[f'a{n}'], language='python') 116 | 117 | # Delete file if one with the same name is found 118 | if os.path.exists(destination_filename): 119 | os.remove(destination_filename) 120 | 121 | # Write sequence to file 122 | mdfile.create_md_file() 123 | 124 | 125 | def create_rst(destination_filename, with_ints=False, with_answers=False): 126 | # TODO: use rstdoc python library. 127 | # also see possible integrations with https://github.com/rougier/numpy-100/pull/38 128 | pass 129 | 130 | 131 | if __name__ == '__main__': 132 | create_jupyter_notebook() 133 | create_jupyter_notebook_random_question() 134 | create_markdown() 135 | create_markdown(with_hints=False, with_solutions=True) 136 | create_markdown(with_hints=True, with_solutions=False) 137 | create_markdown(with_hints=True, with_solutions=True) 138 | -------------------------------------------------------------------------------- /initialise.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | import generators as ge 4 | 5 | 6 | def question(n): 7 | print(f'{n}. ' + ge.QHA[f'q{n}']) 8 | 9 | 10 | def hint(n): 11 | print(ge.QHA[f'h{n}']) 12 | 13 | 14 | def answer(n): 15 | print(ge.QHA[f'a{n}']) 16 | 17 | 18 | def pick(): 19 | n = np.random.randint(1, 100) 20 | question(n) 21 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | numpy 2 | mdutils 3 | nbformat 4 | -------------------------------------------------------------------------------- /runtime.txt: -------------------------------------------------------------------------------- 1 | python-3.7.17 2 | -------------------------------------------------------------------------------- /source/exercises100.ktx: -------------------------------------------------------------------------------- 1 | < q1 2 | Import the numpy package under the name `np` (★☆☆) 3 | 4 | < h1 5 | hint: import … as 6 | 7 | < a1 8 | import numpy as np 9 | 10 | < q2 11 | Print the numpy version and the configuration (★☆☆) 12 | 13 | < h2 14 | hint: np.__version__, np.show_config) 15 | 16 | < a2 17 | print(np.__version__) 18 | np.show_config() 19 | 20 | < q3 21 | Create a null vector of size 10 (★☆☆) 22 | 23 | < h3 24 | hint: np.zeros 25 | 26 | < a3 27 | Z = np.zeros(10) 28 | print(Z) 29 | 30 | < q4 31 | How to find the memory size of any array (★☆☆) 32 | 33 | < h4 34 | hint: size, itemsize 35 | 36 | < a4 37 | Z = np.zeros((10,10)) 38 | print("%d bytes" % (Z.size * Z.itemsize)) 39 | 40 | < q5 41 | How to get the documentation of the numpy add function from the command line? (★☆☆) 42 | 43 | < h5 44 | hint: np.info 45 | 46 | < a5 47 | %run `python -c "import numpy; numpy.info(numpy.add)"` 48 | 49 | < q6 50 | Create a null vector of size 10 but the fifth value which is 1 (★☆☆) 51 | 52 | < h6 53 | hint: array[4] 54 | 55 | < a6 56 | Z = np.zeros(10) 57 | Z[4] = 1 58 | print(Z) 59 | 60 | < q7 61 | Create a vector with values ranging from 10 to 49 (★☆☆) 62 | 63 | < h7 64 | hint: arange 65 | 66 | < a7 67 | Z = np.arange(10,50) 68 | print(Z) 69 | 70 | < q8 71 | Reverse a vector (first element becomes last) (★☆☆) 72 | 73 | < h8 74 | hint: array[::-1] 75 | 76 | < a8 77 | Z = np.arange(50) 78 | Z = Z[::-1] 79 | print(Z) 80 | 81 | < q9 82 | Create a 3x3 matrix with values ranging from 0 to 8 (★☆☆) 83 | 84 | < h9 85 | hint: reshape 86 | 87 | < a9 88 | Z = np.arange(9).reshape(3, 3) 89 | print(Z) 90 | 91 | < q10 92 | Find indices of non-zero elements from [1,2,0,0,4,0] (★☆☆) 93 | 94 | < h10 95 | hint: np.nonzero 96 | 97 | < a10 98 | nz = np.nonzero([1,2,0,0,4,0]) 99 | print(nz) 100 | 101 | < q11 102 | Create a 3x3 identity matrix (★☆☆) 103 | 104 | < h11 105 | hint: np.eye 106 | 107 | < a11 108 | Z = np.eye(3) 109 | print(Z) 110 | 111 | < q12 112 | Create a 3x3x3 array with random values (★☆☆) 113 | 114 | < h12 115 | hint: np.random.random 116 | 117 | < a12 118 | Z = np.random.random((3,3,3)) 119 | print(Z) 120 | 121 | < q13 122 | Create a 10x10 array with random values and find the minimum and maximum values (★☆☆) 123 | 124 | < h13 125 | hint: min, max 126 | 127 | < a13 128 | Z = np.random.random((10,10)) 129 | Zmin, Zmax = Z.min(), Z.max() 130 | print(Zmin, Zmax) 131 | 132 | < q14 133 | Create a random vector of size 30 and find the mean value (★☆☆) 134 | 135 | < h14 136 | hint: mean 137 | 138 | < a14 139 | Z = np.random.random(30) 140 | m = Z.mean() 141 | print(m) 142 | 143 | < q15 144 | Create a 2d array with 1 on the border and 0 inside (★☆☆) 145 | 146 | < h15 147 | hint: array[1:-1, 1:-1] 148 | 149 | < a15 150 | Z = np.ones((10,10)) 151 | Z[1:-1,1:-1] = 0 152 | print(Z) 153 | 154 | < q16 155 | How to add a border (filled with 0's) around an existing array? (★☆☆) 156 | 157 | < h16 158 | hint: np.pad 159 | 160 | < a16 161 | Z = np.ones((5,5)) 162 | Z = np.pad(Z, pad_width=1, mode='constant', constant_values=0) 163 | print(Z) 164 | 165 | # Using fancy indexing 166 | Z[:, [0, -1]] = 0 167 | Z[[0, -1], :] = 0 168 | print(Z) 169 | 170 | < q17 171 | What is the result of the following expression? (★☆☆) 172 | ```python 173 | 0 * np.nan 174 | np.nan == np.nan 175 | np.inf > np.nan 176 | np.nan - np.nan 177 | np.nan in set([np.nan]) 178 | 0.3 == 3 * 0.1 179 | ``` 180 | 181 | < h17 182 | hint: NaN = not a number, inf = infinity 183 | 184 | < a17 185 | print(0 * np.nan) 186 | print(np.nan == np.nan) 187 | print(np.inf > np.nan) 188 | print(np.nan - np.nan) 189 | print(np.nan in set([np.nan])) 190 | print(0.3 == 3 * 0.1) 191 | 192 | < q18 193 | Create a 5x5 matrix with values 1,2,3,4 just below the diagonal (★☆☆) 194 | 195 | < h18 196 | hint: np.diag 197 | 198 | < a18 199 | Z = np.diag(1+np.arange(4),k=-1) 200 | print(Z) 201 | 202 | < q19 203 | Create a 8x8 matrix and fill it with a checkerboard pattern (★☆☆) 204 | 205 | < h19 206 | hint: array[::2] 207 | 208 | < a19 209 | Z = np.zeros((8,8),dtype=int) 210 | Z[1::2,::2] = 1 211 | Z[::2,1::2] = 1 212 | print(Z) 213 | 214 | < q20 215 | Consider a (6,7,8) shape array, what is the index (x,y,z) of the 100th element? (★☆☆) 216 | 217 | < h20 218 | hint: np.unravel_index 219 | 220 | < a20 221 | print(np.unravel_index(99,(6,7,8))) 222 | 223 | < q21 224 | Create a checkerboard 8x8 matrix using the tile function (★☆☆) 225 | 226 | < h21 227 | hint: np.tile 228 | 229 | < a21 230 | Z = np.tile( np.array([[0,1],[1,0]]), (4,4)) 231 | print(Z) 232 | 233 | < q22 234 | Normalize a 5x5 random matrix (★☆☆) 235 | 236 | < h22 237 | hint: (x -mean)/std 238 | 239 | < a22 240 | Z = np.random.random((5,5)) 241 | Z = (Z - np.mean (Z)) / (np.std (Z)) 242 | print(Z) 243 | 244 | < q23 245 | Create a custom dtype that describes a color as four unsigned bytes (RGBA) (★☆☆) 246 | 247 | < h23 248 | hint: np.dtype 249 | 250 | < a23 251 | color = np.dtype([("r", np.ubyte), 252 | ("g", np.ubyte), 253 | ("b", np.ubyte), 254 | ("a", np.ubyte)]) 255 | 256 | < q24 257 | Multiply a 5x3 matrix by a 3x2 matrix (real matrix product) (★☆☆) 258 | 259 | < h24 260 | hint: 261 | 262 | < a24 263 | Z = np.matmul(np.ones((5, 3)), np.ones((3, 2))) 264 | print(Z) 265 | 266 | # Alternative solution, in Python 3.5 and above 267 | Z = np.ones((5,3)) @ np.ones((3,2)) 268 | print(Z) 269 | 270 | < q25 271 | Given a 1D array, negate all elements which are between 3 and 8, in place. (★☆☆) 272 | 273 | < h25 274 | hint: >, < 275 | 276 | < a25 277 | # Author: Evgeni Burovski 278 | 279 | Z = np.arange(11) 280 | Z[(3 < Z) & (Z < 8)] *= -1 281 | print(Z) 282 | 283 | < q26 284 | What is the output of the following script? (★☆☆) 285 | ```python 286 | # Author: Jake VanderPlas 287 | 288 | print(sum(range(5),-1)) 289 | from numpy import * 290 | print(sum(range(5),-1)) 291 | ``` 292 | 293 | < h26 294 | hint: np.sum 295 | 296 | < a26 297 | # Author: Jake VanderPlas 298 | 299 | print(sum(range(5),-1)) 300 | from numpy import * 301 | print(sum(range(5),-1)) 302 | 303 | < q27 304 | Consider an integer vector Z, which of these expressions are legal? (★☆☆) 305 | ```python 306 | Z**Z 307 | 2 << Z >> 2 308 | Z <- Z 309 | 1j*Z 310 | Z/1/1 311 | ZZ 312 | ``` 313 | 314 | < h27 315 | No hints provided... 316 | 317 | < a27 318 | Z**Z 319 | 2 << Z >> 2 320 | Z <- Z 321 | 1j*Z 322 | Z/1/1 323 | ZZ 324 | 325 | < q28 326 | What are the result of the following expressions? (★☆☆) 327 | ```python 328 | np.array(0) / np.array(0) 329 | np.array(0) // np.array(0) 330 | np.array([np.nan]).astype(int).astype(float) 331 | ``` 332 | 333 | < h28 334 | No hints provided... 335 | 336 | < a28 337 | print(np.array(0) / np.array(0)) 338 | print(np.array(0) // np.array(0)) 339 | print(np.array([np.nan]).astype(int).astype(float)) 340 | 341 | < q29 342 | How to round away from zero a float array ? (★☆☆) 343 | 344 | < h29 345 | hint: np.uniform, np.copysign, np.ceil, np.abs, np.where 346 | 347 | < a29 348 | # Author: Charles R Harris 349 | 350 | Z = np.random.uniform(-10,+10,10) 351 | print(np.copysign(np.ceil(np.abs(Z)), Z)) 352 | 353 | # More readable but less efficient 354 | print(np.where(Z>0, np.ceil(Z), np.floor(Z))) 355 | 356 | < q30 357 | How to find common values between two arrays? (★☆☆) 358 | 359 | < h30 360 | hint: np.intersect1d 361 | 362 | < a30 363 | Z1 = np.random.randint(0,10,10) 364 | Z2 = np.random.randint(0,10,10) 365 | print(np.intersect1d(Z1,Z2)) 366 | 367 | < q31 368 | How to ignore all numpy warnings (not recommended)? (★☆☆) 369 | 370 | < h31 371 | hint: np.seterr, np.errstate 372 | 373 | < a31 374 | # Suicide mode on 375 | defaults = np.seterr(all="ignore") 376 | Z = np.ones(1) / 0 377 | 378 | # Back to sanity 379 | _ = np.seterr(**defaults) 380 | 381 | # Equivalently with a context manager 382 | with np.errstate(all="ignore"): 383 | np.arange(3) / 0 384 | 385 | < q32 386 | Is the following expressions true? (★☆☆) 387 | ```python 388 | np.sqrt(-1) == np.emath.sqrt(-1) 389 | ``` 390 | 391 | < h32 392 | hint: imaginary number 393 | 394 | < a32 395 | np.sqrt(-1) == np.emath.sqrt(-1) 396 | 397 | < q33 398 | How to get the dates of yesterday, today and tomorrow? (★☆☆) 399 | 400 | < h33 401 | hint: np.datetime64, np.timedelta64 402 | 403 | < a33 404 | yesterday = np.datetime64('today') - np.timedelta64(1) 405 | today = np.datetime64('today') 406 | tomorrow = np.datetime64('today') + np.timedelta64(1) 407 | 408 | < q34 409 | How to get all the dates corresponding to the month of July 2016? (★★☆) 410 | 411 | < h34 412 | hint: np.arange(dtype=datetime64['D']) 413 | 414 | < a34 415 | Z = np.arange('2016-07', '2016-08', dtype='datetime64[D]') 416 | print(Z) 417 | 418 | < q35 419 | How to compute ((A+B)*(-A/2)) in place (without copy)? (★★☆) 420 | 421 | < h35 422 | hint: np.add(out=), np.negative(out=), np.multiply(out=), np.divide(out=) 423 | 424 | < a35 425 | A = np.ones(3)*1 426 | B = np.ones(3)*2 427 | np.add(A,B,out=B) 428 | np.divide(A,2,out=A) 429 | np.negative(A,out=A) 430 | np.multiply(A,B,out=A) 431 | 432 | < q36 433 | Extract the integer part of a random array of positive numbers using 4 different methods (★★☆) 434 | 435 | < h36 436 | hint: %, np.floor, astype, np.trunc 437 | 438 | < a36 439 | Z = np.random.uniform(0,10,10) 440 | 441 | print(Z - Z%1) 442 | print(Z // 1) 443 | print(np.floor(Z)) 444 | print(Z.astype(int)) 445 | print(np.trunc(Z)) 446 | 447 | < q37 448 | Create a 5x5 matrix with row values ranging from 0 to 4 (★★☆) 449 | 450 | < h37 451 | hint: np.arange 452 | 453 | < a37 454 | Z = np.zeros((5,5)) 455 | Z += np.arange(5) 456 | print(Z) 457 | 458 | # without broadcasting 459 | Z = np.tile(np.arange(0, 5), (5,1)) 460 | print(Z) 461 | 462 | < q38 463 | Consider a generator function that generates 10 integers and use it to build an array (★☆☆) 464 | 465 | < h38 466 | hint: np.fromiter 467 | 468 | < a38 469 | def generate(): 470 | for x in range(10): 471 | yield x 472 | Z = np.fromiter(generate(),dtype=float,count=-1) 473 | print(Z) 474 | 475 | < q39 476 | Create a vector of size 10 with values ranging from 0 to 1, both excluded (★★☆) 477 | 478 | < h39 479 | hint: np.linspace 480 | 481 | < a39 482 | Z = np.linspace(0,1,11,endpoint=False)[1:] 483 | print(Z) 484 | 485 | < q40 486 | Create a random vector of size 10 and sort it (★★☆) 487 | 488 | < h40 489 | hint: sort 490 | 491 | < a40 492 | Z = np.random.random(10) 493 | Z.sort() 494 | print(Z) 495 | 496 | < q41 497 | How to sum a small array faster than np.sum? (★★☆) 498 | 499 | < h41 500 | hint: np.add.reduce 501 | 502 | < a41 503 | # Author: Evgeni Burovski 504 | 505 | Z = np.arange(10) 506 | np.add.reduce(Z) 507 | 508 | < q42 509 | Consider two random arrays A and B, check if they are equal (★★☆) 510 | 511 | < h42 512 | hint: np.allclose, np.array_equal 513 | 514 | < a42 515 | A = np.random.randint(0,2,5) 516 | B = np.random.randint(0,2,5) 517 | 518 | # Assuming identical shape of the arrays and a tolerance for the comparison of values 519 | equal = np.allclose(A,B) 520 | print(equal) 521 | 522 | # Checking both the shape and the element values, no tolerance (values have to be exactly equal) 523 | equal = np.array_equal(A,B) 524 | print(equal) 525 | 526 | < q43 527 | Make an array immutable (read-only) (★★☆) 528 | 529 | < h43 530 | hint: flags.writeable 531 | 532 | < a43 533 | Z = np.zeros(10) 534 | Z.flags.writeable = False 535 | Z[0] = 1 536 | 537 | < q44 538 | Consider a random 10x2 matrix representing cartesian coordinates, convert them to polar coordinates (★★☆) 539 | 540 | < h44 541 | hint: np.sqrt, np.arctan2 542 | 543 | < a44 544 | Z = np.random.random((10,2)) 545 | X,Y = Z[:,0], Z[:,1] 546 | R = np.sqrt(X**2+Y**2) 547 | T = np.arctan2(Y,X) 548 | print(R) 549 | print(T) 550 | 551 | < q45 552 | Create random vector of size 10 and replace the maximum value by 0 (★★☆) 553 | 554 | < h45 555 | hint: argmax 556 | 557 | < a45 558 | Z = np.random.random(10) 559 | Z[Z.argmax()] = 0 560 | print(Z) 561 | 562 | < q46 563 | Create a structured array with `x` and `y` coordinates covering the [0,1]x[0,1] area (★★☆) 564 | 565 | < h46 566 | hint: np.meshgrid 567 | 568 | < a46 569 | Z = np.zeros((5,5), [('x',float),('y',float)]) 570 | Z['x'], Z['y'] = np.meshgrid(np.linspace(0,1,5), 571 | np.linspace(0,1,5)) 572 | print(Z) 573 | 574 | < q47 575 | Given two arrays, X and Y, construct the Cauchy matrix C (Cij =1/(xi - yj)) (★★☆) 576 | 577 | < h47 578 | hint: np.subtract.outer 579 | 580 | < a47 581 | # Author: Evgeni Burovski 582 | 583 | X = np.arange(8) 584 | Y = X + 0.5 585 | C = 1.0 / np.subtract.outer(X, Y) 586 | print(np.linalg.det(C)) 587 | 588 | < q48 589 | Print the minimum and maximum representable values for each numpy scalar type (★★☆) 590 | 591 | < h48 592 | hint: np.iinfo, np.finfo, eps 593 | 594 | < a48 595 | for dtype in [np.int8, np.int32, np.int64]: 596 | print(np.iinfo(dtype).min) 597 | print(np.iinfo(dtype).max) 598 | for dtype in [np.float32, np.float64]: 599 | print(np.finfo(dtype).min) 600 | print(np.finfo(dtype).max) 601 | print(np.finfo(dtype).eps) 602 | 603 | < q49 604 | How to print all the values of an array? (★★☆) 605 | 606 | < h49 607 | hint: np.set_printoptions 608 | 609 | < a49 610 | np.set_printoptions(threshold=float("inf")) 611 | Z = np.zeros((40,40)) 612 | print(Z) 613 | 614 | < q50 615 | How to find the closest value (to a given scalar) in a vector? (★★☆) 616 | 617 | < h50 618 | hint: argmin 619 | 620 | < a50 621 | Z = np.arange(100) 622 | v = np.random.uniform(0,100) 623 | index = (np.abs(Z-v)).argmin() 624 | print(Z[index]) 625 | 626 | < q51 627 | Create a structured array representing a position (x,y) and a color (r,g,b) (★★☆) 628 | 629 | < h51 630 | hint: dtype 631 | 632 | < a51 633 | Z = np.zeros(10, [ ('position', [ ('x', float, 1), 634 | ('y', float, 1)]), 635 | ('color', [ ('r', float, 1), 636 | ('g', float, 1), 637 | ('b', float, 1)])]) 638 | print(Z) 639 | 640 | < q52 641 | Consider a random vector with shape (100,2) representing coordinates, find point by point distances (★★☆) 642 | 643 | < h52 644 | hint: np.atleast_2d, T, np.sqrt 645 | 646 | < a52 647 | Z = np.random.random((10,2)) 648 | X,Y = np.atleast_2d(Z[:,0], Z[:,1]) 649 | D = np.sqrt( (X-X.T)**2 + (Y-Y.T)**2) 650 | print(D) 651 | 652 | # Much faster with scipy 653 | import scipy 654 | # Thanks Gavin Heverly-Coulson (#issue 1) 655 | import scipy.spatial 656 | 657 | Z = np.random.random((10,2)) 658 | D = scipy.spatial.distance.cdist(Z,Z) 659 | print(D) 660 | 661 | < q53 662 | How to convert a float (32 bits) array into an integer (32 bits) array in place? 663 | 664 | < h53 665 | hint: view and [:] = 666 | 667 | < a53 668 | # Thanks Vikas (https://stackoverflow.com/a/10622758/5989906) 669 | # & unutbu (https://stackoverflow.com/a/4396247/5989906) 670 | Z = (np.random.rand(10)*100).astype(np.float32) 671 | Y = Z.view(np.int32) 672 | Y[:] = Z 673 | print(Y) 674 | 675 | < q54 676 | How to read the following file? (★★☆) 677 | ``` 678 | 1, 2, 3, 4, 5 679 | 6, , , 7, 8 680 | , , 9,10,11 681 | ``` 682 | 683 | < h54 684 | hint: np.genfromtxt 685 | 686 | < a54 687 | from io import StringIO 688 | 689 | # Fake file 690 | s = StringIO('''1, 2, 3, 4, 5 691 | 692 | 6, , , 7, 8 693 | 694 | , , 9,10,11 695 | ''') 696 | Z = np.genfromtxt(s, delimiter=",", dtype=np.int) 697 | print(Z) 698 | 699 | < q55 700 | What is the equivalent of enumerate for numpy arrays? (★★☆) 701 | 702 | < h55 703 | hint: np.ndenumerate, np.ndindex 704 | 705 | < a55 706 | Z = np.arange(9).reshape(3,3) 707 | for index, value in np.ndenumerate(Z): 708 | print(index, value) 709 | for index in np.ndindex(Z.shape): 710 | print(index, Z[index]) 711 | 712 | < q56 713 | Generate a generic 2D Gaussian-like array (★★☆) 714 | 715 | < h56 716 | hint: np.meshgrid, np.exp 717 | 718 | < a56 719 | X, Y = np.meshgrid(np.linspace(-1,1,10), np.linspace(-1,1,10)) 720 | D = np.sqrt(X*X+Y*Y) 721 | sigma, mu = 1.0, 0.0 722 | G = np.exp(-( (D-mu)**2 / ( 2.0 * sigma**2 ) ) ) 723 | print(G) 724 | 725 | < q57 726 | How to randomly place p elements in a 2D array? (★★☆) 727 | 728 | < h57 729 | hint: np.put, np.random.choice 730 | 731 | < a57 732 | # Author: Divakar 733 | 734 | n = 10 735 | p = 3 736 | Z = np.zeros((n,n)) 737 | np.put(Z, np.random.choice(range(n*n), p, replace=False),1) 738 | print(Z) 739 | 740 | < q58 741 | Subtract the mean of each row of a matrix (★★☆) 742 | 743 | < h58 744 | hint: mean(axis=,keepdims=) 745 | 746 | < a58 747 | # Author: Warren Weckesser 748 | 749 | X = np.random.rand(5, 10) 750 | 751 | # Recent versions of numpy 752 | Y = X - X.mean(axis=1, keepdims=True) 753 | 754 | # Older versions of numpy 755 | Y = X - X.mean(axis=1).reshape(-1, 1) 756 | 757 | print(Y) 758 | 759 | < q59 760 | How to sort an array by the nth column? (★★☆) 761 | 762 | < h59 763 | hint: argsort 764 | 765 | < a59 766 | # Author: Steve Tjoa 767 | 768 | Z = np.random.randint(0,10,(3,3)) 769 | print(Z) 770 | print(Z[Z[:,1].argsort()]) 771 | 772 | < q60 773 | How to tell if a given 2D array has null columns? (★★☆) 774 | 775 | < h60 776 | hint: any, ~ 777 | 778 | < a60 779 | # Author: Warren Weckesser 780 | 781 | # null : 0 782 | Z = np.random.randint(0,3,(3,10)) 783 | print((~Z.any(axis=0)).any()) 784 | 785 | # null : np.nan 786 | Z=np.array([ 787 | [0,1,np.nan], 788 | [1,2,np.nan], 789 | [4,5,np.nan] 790 | ]) 791 | print(np.isnan(Z).all(axis=0)) 792 | 793 | < q61 794 | Find the nearest value from a given value in an array (★★☆) 795 | 796 | < h61 797 | hint: np.abs, argmin, flat 798 | 799 | < a61 800 | Z = np.random.uniform(0,1,10) 801 | z = 0.5 802 | m = Z.flat[np.abs(Z - z).argmin()] 803 | print(m) 804 | 805 | < q62 806 | Considering two arrays with shape (1,3) and (3,1), how to compute their sum using an iterator? (★★☆) 807 | 808 | < h62 809 | hint: np.nditer 810 | 811 | < a62 812 | A = np.arange(3).reshape(3,1) 813 | B = np.arange(3).reshape(1,3) 814 | it = np.nditer([A,B,None]) 815 | for x,y,z in it: z[...] = x + y 816 | print(it.operands[2]) 817 | 818 | < q63 819 | Create an array class that has a name attribute (★★☆) 820 | 821 | < h63 822 | hint: class method 823 | 824 | < a63 825 | class NamedArray(np.ndarray): 826 | def __new__(cls, array, name="no name"): 827 | obj = np.asarray(array).view(cls) 828 | obj.name = name 829 | return obj 830 | def __array_finalize__(self, obj): 831 | if obj is None: return 832 | self.name = getattr(obj, 'name', "no name") 833 | 834 | Z = NamedArray(np.arange(10), "range_10") 835 | print (Z.name) 836 | 837 | < q64 838 | Consider a given vector, how to add 1 to each element indexed by a second vector (be careful with repeated indices)? (★★★) 839 | 840 | < h64 841 | hint: np.bincount | np.add.at 842 | 843 | < a64 844 | # Author: Brett Olsen 845 | 846 | Z = np.ones(10) 847 | I = np.random.randint(0,len(Z),20) 848 | Z += np.bincount(I, minlength=len(Z)) 849 | print(Z) 850 | 851 | # Another solution 852 | # Author: Bartosz Telenczuk 853 | np.add.at(Z, I, 1) 854 | print(Z) 855 | 856 | < q65 857 | How to accumulate elements of a vector (X) to an array (F) based on an index list (I)? (★★★) 858 | 859 | < h65 860 | hint: np.bincount 861 | 862 | < a65 863 | # Author: Alan G Isaac 864 | 865 | X = [1,2,3,4,5,6] 866 | I = [1,3,9,3,4,1] 867 | F = np.bincount(I,X) 868 | print(F) 869 | 870 | < q66 871 | Considering a (w,h,3) image of (dtype=ubyte), compute the number of unique colors (★★☆) 872 | 873 | < h66 874 | hint: np.unique 875 | 876 | < a66 877 | # Author: Fisher Wang 878 | 879 | w, h = 256, 256 880 | I = np.random.randint(0, 4, (h, w, 3)).astype(np.ubyte) 881 | colors = np.unique(I.reshape(-1, 3), axis=0) 882 | n = len(colors) 883 | print(n) 884 | 885 | # Faster version 886 | # Author: Mark Setchell 887 | # https://stackoverflow.com/a/59671950/2836621 888 | 889 | w, h = 256, 256 890 | I = np.random.randint(0,4,(h,w,3), dtype=np.uint8) 891 | 892 | # View each pixel as a single 24-bit integer, rather than three 8-bit bytes 893 | I24 = np.dot(I.astype(np.uint32),[1,256,65536]) 894 | 895 | # Count unique colours 896 | n = len(np.unique(I24)) 897 | print(n) 898 | 899 | < q67 900 | Considering a four dimensions array, how to get sum over the last two axis at once? (★★★) 901 | 902 | < h67 903 | hint: sum(axis=(-2,-1)) 904 | 905 | < a67 906 | A = np.random.randint(0,10,(3,4,3,4)) 907 | # solution by passing a tuple of axes (introduced in numpy 1.7.0) 908 | sum = A.sum(axis=(-2,-1)) 909 | print(sum) 910 | # solution by flattening the last two dimensions into one 911 | # (useful for functions that don't accept tuples for axis argument) 912 | sum = A.reshape(A.shape[:-2] + (-1,)).sum(axis=-1) 913 | print(sum) 914 | 915 | < q68 916 | Considering a one-dimensional vector D, how to compute means of subsets of D using a vector S of same size describing subset indices? (★★★) 917 | 918 | < h68 919 | hint: np.bincount 920 | 921 | < a68 922 | # Author: Jaime Fernández del Río 923 | 924 | D = np.random.uniform(0,1,100) 925 | S = np.random.randint(0,10,100) 926 | D_sums = np.bincount(S, weights=D) 927 | D_counts = np.bincount(S) 928 | D_means = D_sums / D_counts 929 | print(D_means) 930 | 931 | # Pandas solution as a reference due to more intuitive code 932 | import pandas as pd 933 | print(pd.Series(D).groupby(S).mean()) 934 | 935 | < q69 936 | How to get the diagonal of a dot product? (★★★) 937 | 938 | < h69 939 | hint: np.diag 940 | 941 | < a69 942 | # Author: Mathieu Blondel 943 | 944 | A = np.random.uniform(0,1,(5,5)) 945 | B = np.random.uniform(0,1,(5,5)) 946 | 947 | # Slow version 948 | np.diag(np.dot(A, B)) 949 | 950 | # Fast version 951 | np.sum(A * B.T, axis=1) 952 | 953 | # Faster version 954 | np.einsum("ij,ji->i", A, B) 955 | 956 | < q70 957 | Consider the vector [1, 2, 3, 4, 5], how to build a new vector with 3 consecutive zeros interleaved between each value? (★★★) 958 | 959 | < h70 960 | hint: array[::4] 961 | 962 | < a70 963 | # Author: Warren Weckesser 964 | 965 | Z = np.array([1,2,3,4,5]) 966 | nz = 3 967 | Z0 = np.zeros(len(Z) + (len(Z)-1)*(nz)) 968 | Z0[::nz+1] = Z 969 | print(Z0) 970 | 971 | < q71 972 | Consider an array of dimension (5,5,3), how to multiply it by an array with dimensions (5,5)? (★★★) 973 | 974 | < h71 975 | hint: array[:, :, None] 976 | 977 | < a71 978 | A = np.ones((5,5,3)) 979 | B = 2*np.ones((5,5)) 980 | print(A * B[:,:,None]) 981 | 982 | < q72 983 | How to swap two rows of an array? (★★★) 984 | 985 | < h72 986 | hint: array[[]] = array[[]] 987 | 988 | < a72 989 | # Author: Eelco Hoogendoorn 990 | 991 | A = np.arange(25).reshape(5,5) 992 | A[[0,1]] = A[[1,0]] 993 | print(A) 994 | 995 | < q73 996 | Consider a set of 10 triplets describing 10 triangles (with shared vertices), find the set of unique line segments composing all the triangles (★★★) 997 | 998 | < h73 999 | hint: repeat, np.roll, np.sort, view, np.unique 1000 | 1001 | < a73 1002 | # Author: Nicolas P. Rougier 1003 | 1004 | faces = np.random.randint(0,100,(10,3)) 1005 | F = np.roll(faces.repeat(2,axis=1),-1,axis=1) 1006 | F = F.reshape(len(F)*3,2) 1007 | F = np.sort(F,axis=1) 1008 | G = F.view( dtype=[('p0',F.dtype),('p1',F.dtype)] ) 1009 | G = np.unique(G) 1010 | print(G) 1011 | 1012 | < q74 1013 | Given a sorted array C that corresponds to a bincount, how to produce an array A such that np.bincount(A) == C? (★★★) 1014 | 1015 | < h74 1016 | hint: np.repeat 1017 | 1018 | < a74 1019 | # Author: Jaime Fernández del Río 1020 | 1021 | C = np.bincount([1,1,2,3,4,4,6]) 1022 | A = np.repeat(np.arange(len(C)), C) 1023 | print(A) 1024 | 1025 | < q75 1026 | How to compute averages using a sliding window over an array? (★★★) 1027 | 1028 | < h75 1029 | hint: np.cumsum, from numpy.lib.stride_tricks import sliding_window_view (np>=1.20.0) 1030 | 1031 | < a75 1032 | # Author: Jaime Fernández del Río 1033 | 1034 | def moving_average(a, n=3) : 1035 | ret = np.cumsum(a, dtype=float) 1036 | ret[n:] = ret[n:] - ret[:-n] 1037 | return ret[n - 1:] / n 1038 | Z = np.arange(20) 1039 | print(moving_average(Z, n=3)) 1040 | 1041 | # Author: Jeff Luo (@Jeff1999) 1042 | # make sure your NumPy >= 1.20.0 1043 | 1044 | from numpy.lib.stride_tricks import sliding_window_view 1045 | 1046 | Z = np.arange(20) 1047 | print(sliding_window_view(Z, window_shape=3).mean(axis=-1)) 1048 | 1049 | < q76 1050 | 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]) (★★★) 1051 | 1052 | < h76 1053 | hint: from numpy.lib import stride_tricks, from numpy.lib.stride_tricks import sliding_window_view (np>=1.20.0) 1054 | 1055 | < a76 1056 | # Author: Joe Kington / Erik Rigtorp 1057 | from numpy.lib import stride_tricks 1058 | 1059 | def rolling(a, window): 1060 | shape = (a.size - window + 1, window) 1061 | strides = (a.strides[0], a.strides[0]) 1062 | return stride_tricks.as_strided(a, shape=shape, strides=strides) 1063 | Z = rolling(np.arange(10), 3) 1064 | print(Z) 1065 | 1066 | # Author: Jeff Luo (@Jeff1999) 1067 | 1068 | Z = np.arange(10) 1069 | print(sliding_window_view(Z, window_shape=3)) 1070 | 1071 | < q77 1072 | How to negate a boolean, or to change the sign of a float inplace? (★★★) 1073 | 1074 | < h77 1075 | hint: np.logical_not, np.negative 1076 | 1077 | < a77 1078 | # Author: Nathaniel J. Smith 1079 | 1080 | Z = np.random.randint(0,2,100) 1081 | np.logical_not(Z, out=Z) 1082 | 1083 | Z = np.random.uniform(-1.0,1.0,100) 1084 | np.negative(Z, out=Z) 1085 | 1086 | < q78 1087 | 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])? (★★★) 1088 | 1089 | < h78 1090 | No hints provided... 1091 | 1092 | < a78 1093 | def distance(P0, P1, p): 1094 | T = P1 - P0 1095 | L = (T**2).sum(axis=1) 1096 | U = -((P0[:,0]-p[...,0])*T[:,0] + (P0[:,1]-p[...,1])*T[:,1]) / L 1097 | U = U.reshape(len(U),1) 1098 | D = P0 + U*T - p 1099 | return np.sqrt((D**2).sum(axis=1)) 1100 | 1101 | P0 = np.random.uniform(-10,10,(10,2)) 1102 | P1 = np.random.uniform(-10,10,(10,2)) 1103 | p = np.random.uniform(-10,10,( 1,2)) 1104 | print(distance(P0, P1, p)) 1105 | 1106 | < q79 1107 | 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])? (★★★) 1108 | 1109 | < h79 1110 | No hints provided... 1111 | 1112 | < a79 1113 | # Author: Italmassov Kuanysh 1114 | 1115 | # based on distance function from previous question 1116 | P0 = np.random.uniform(-10, 10, (10,2)) 1117 | P1 = np.random.uniform(-10,10,(10,2)) 1118 | p = np.random.uniform(-10, 10, (10,2)) 1119 | print(np.array([distance(P0,P1,p_i) for p_i in p])) 1120 | 1121 | # Author: Yang Wu (Broadcasting) 1122 | def distance_points_to_lines(p: np.ndarray, p_1: np.ndarray, p_2: np.ndarray) -> np.ndarray: 1123 | x_0, y_0 = p.T # Shape -> (n points, ) 1124 | x_1, y_1 = p_1.T # Shape -> (n lines, ) 1125 | x_2, y_2 = p_2.T # Shape -> (n lines, ) 1126 | 1127 | # Displacement vector coordinates from p_1 -> p_2 1128 | dx = x_2 - x_1 # Shape -> (n lines, ) 1129 | dy = y_2 - y_1 # Shape -> (n lines, ) 1130 | 1131 | # The 'cross product' term 1132 | cross_term = x_2 * y_1 - y_2 * x_1 # Shape -> (n lines, ) 1133 | 1134 | # Broadcast x_0, y_0 (n points, 1) and dx, dy, cross_term (1, n lines) -> (n points, n lines) 1135 | numerator = np.abs( 1136 | dy[np.newaxis, :] * x_0[:, np.newaxis] 1137 | - dx[np.newaxis, :] * y_0[:, np.newaxis] 1138 | + cross_term[np.newaxis, :] 1139 | ) 1140 | denominator = np.sqrt(dx**2 + dy**2) # Shape -> (n lines, ) 1141 | 1142 | # Shape (n points, n lines) / (1, n_lines) -> (n points, n lines) 1143 | return numerator / denominator[np.newaxis, :] 1144 | 1145 | distance_points_to_lines(p, P0, P1) 1146 | 1147 | < q80 1148 | 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) (★★★) 1149 | 1150 | < h80 1151 | hint: minimum maximum 1152 | 1153 | < a80 1154 | # Author: Nicolas Rougier 1155 | 1156 | Z = np.random.randint(0,10,(10,10)) 1157 | shape = (5,5) 1158 | fill = 0 1159 | position = (1,1) 1160 | 1161 | R = np.ones(shape, dtype=Z.dtype)*fill 1162 | P = np.array(list(position)).astype(int) 1163 | Rs = np.array(list(R.shape)).astype(int) 1164 | Zs = np.array(list(Z.shape)).astype(int) 1165 | 1166 | R_start = np.zeros((len(shape),)).astype(int) 1167 | R_stop = np.array(list(shape)).astype(int) 1168 | Z_start = (P-Rs//2) 1169 | Z_stop = (P+Rs//2)+Rs%2 1170 | 1171 | R_start = (R_start - np.minimum(Z_start,0)).tolist() 1172 | Z_start = (np.maximum(Z_start,0)).tolist() 1173 | R_stop = np.maximum(R_start, (R_stop - np.maximum(Z_stop-Zs,0))).tolist() 1174 | Z_stop = (np.minimum(Z_stop,Zs)).tolist() 1175 | 1176 | r = [slice(start,stop) for start,stop in zip(R_start,R_stop)] 1177 | z = [slice(start,stop) for start,stop in zip(Z_start,Z_stop)] 1178 | R[r] = Z[z] 1179 | print(Z) 1180 | print(R) 1181 | 1182 | < q81 1183 | 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]]? (★★★) 1184 | 1185 | < h81 1186 | hint: stride_tricks.as_strided, from numpy.lib.stride_tricks import sliding_window_view (np>=1.20.0) 1187 | 1188 | < a81 1189 | # Author: Stefan van der Walt 1190 | 1191 | Z = np.arange(1,15,dtype=np.uint32) 1192 | R = stride_tricks.as_strided(Z,(11,4),(4,4)) 1193 | print(R) 1194 | 1195 | # Author: Jeff Luo (@Jeff1999) 1196 | 1197 | Z = np.arange(1, 15, dtype=np.uint32) 1198 | print(sliding_window_view(Z, window_shape=4)) 1199 | 1200 | < q82 1201 | Compute a matrix rank (★★★) 1202 | 1203 | < h82 1204 | hint: np.linalg.svd, np.linalg.matrix_rank 1205 | 1206 | < a82 1207 | # Author: Stefan van der Walt 1208 | 1209 | Z = np.random.uniform(0,1,(10,10)) 1210 | U, S, V = np.linalg.svd(Z) # Singular Value Decomposition 1211 | rank = np.sum(S > 1e-10) 1212 | print(rank) 1213 | 1214 | # alternative solution: 1215 | # Author: Jeff Luo (@Jeff1999) 1216 | 1217 | rank = np.linalg.matrix_rank(Z) 1218 | print(rank) 1219 | 1220 | < q83 1221 | How to find the most frequent value in an array? 1222 | 1223 | < h83 1224 | hint: np.bincount, argmax 1225 | 1226 | < a83 1227 | Z = np.random.randint(0,10,50) 1228 | print(np.bincount(Z).argmax()) 1229 | 1230 | < q84 1231 | Extract all the contiguous 3x3 blocks from a random 10x10 matrix (★★★) 1232 | 1233 | < h84 1234 | hint: stride_tricks.as_strided, from numpy.lib.stride_tricks import sliding_window_view (np>=1.20.0) 1235 | 1236 | < a84 1237 | # Author: Chris Barker 1238 | 1239 | Z = np.random.randint(0,5,(10,10)) 1240 | n = 3 1241 | i = 1 + (Z.shape[0]-3) 1242 | j = 1 + (Z.shape[1]-3) 1243 | C = stride_tricks.as_strided(Z, shape=(i, j, n, n), strides=Z.strides + Z.strides) 1244 | print(C) 1245 | 1246 | # Author: Jeff Luo (@Jeff1999) 1247 | 1248 | Z = np.random.randint(0,5,(10,10)) 1249 | print(sliding_window_view(Z, window_shape=(3, 3))) 1250 | 1251 | < q85 1252 | Create a 2D array subclass such that Z[i,j] == Z[j,i] (★★★) 1253 | 1254 | < h85 1255 | hint: class method 1256 | 1257 | < a85 1258 | # Author: Eric O. Lebigot 1259 | # Note: only works for 2d array and value setting using indices 1260 | 1261 | class Symetric(np.ndarray): 1262 | def __setitem__(self, index, value): 1263 | i,j = index 1264 | super(Symetric, self).__setitem__((i,j), value) 1265 | super(Symetric, self).__setitem__((j,i), value) 1266 | 1267 | def symetric(Z): 1268 | return np.asarray(Z + Z.T - np.diag(Z.diagonal())).view(Symetric) 1269 | 1270 | S = symetric(np.random.randint(0,10,(5,5))) 1271 | S[2,3] = 42 1272 | print(S) 1273 | 1274 | < q86 1275 | 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)) (★★★) 1276 | 1277 | < h86 1278 | hint: np.tensordot 1279 | 1280 | < a86 1281 | # Author: Stefan van der Walt 1282 | 1283 | p, n = 10, 20 1284 | M = np.ones((p,n,n)) 1285 | V = np.ones((p,n,1)) 1286 | S = np.tensordot(M, V, axes=[[0, 2], [0, 1]]) 1287 | print(S) 1288 | 1289 | # It works, because: 1290 | # M is (p,n,n) 1291 | # V is (p,n,1) 1292 | # Thus, summing over the paired axes 0 and 0 (of M and V independently), 1293 | # and 2 and 1, to remain with a (n,1) vector. 1294 | 1295 | < q87 1296 | Consider a 16x16 array, how to get the block-sum (block size is 4x4)? (★★★) 1297 | 1298 | < h87 1299 | hint: np.add.reduceat, from numpy.lib.stride_tricks import sliding_window_view (np>=1.20.0) 1300 | 1301 | < a87 1302 | # Author: Robert Kern 1303 | 1304 | Z = np.ones((16,16)) 1305 | k = 4 1306 | S = np.add.reduceat(np.add.reduceat(Z, np.arange(0, Z.shape[0], k), axis=0), 1307 | np.arange(0, Z.shape[1], k), axis=1) 1308 | print(S) 1309 | 1310 | # alternative solution: 1311 | # Author: Sebastian Wallkötter (@FirefoxMetzger) 1312 | 1313 | Z = np.ones((16,16)) 1314 | k = 4 1315 | 1316 | windows = np.lib.stride_tricks.sliding_window_view(Z, (k, k)) 1317 | S = windows[::k, ::k, ...].sum(axis=(-2, -1)) 1318 | 1319 | # Author: Jeff Luo (@Jeff1999) 1320 | 1321 | Z = np.ones((16, 16)) 1322 | k = 4 1323 | print(sliding_window_view(Z, window_shape=(k, k))[::k, ::k].sum(axis=(-2, -1))) 1324 | 1325 | < q88 1326 | How to implement the Game of Life using numpy arrays? (★★★) 1327 | 1328 | < h88 1329 | No hints provided... 1330 | 1331 | < a88 1332 | # Author: Nicolas Rougier 1333 | 1334 | def iterate(Z): 1335 | # Count neighbours 1336 | N = (Z[0:-2,0:-2] + Z[0:-2,1:-1] + Z[0:-2,2:] + 1337 | Z[1:-1,0:-2] + Z[1:-1,2:] + 1338 | Z[2: ,0:-2] + Z[2: ,1:-1] + Z[2: ,2:]) 1339 | 1340 | # Apply rules 1341 | birth = (N==3) & (Z[1:-1,1:-1]==0) 1342 | survive = ((N==2) | (N==3)) & (Z[1:-1,1:-1]==1) 1343 | Z[...] = 0 1344 | Z[1:-1,1:-1][birth | survive] = 1 1345 | return Z 1346 | 1347 | Z = np.random.randint(0,2,(50,50)) 1348 | for i in range(100): Z = iterate(Z) 1349 | print(Z) 1350 | 1351 | < q89 1352 | How to get the n largest values of an array (★★★) 1353 | 1354 | < h89 1355 | hint: np.argsort | np.argpartition 1356 | 1357 | < a89 1358 | Z = np.arange(10000) 1359 | np.random.shuffle(Z) 1360 | n = 5 1361 | 1362 | # Slow 1363 | print (Z[np.argsort(Z)[-n:]]) 1364 | 1365 | # Fast 1366 | print (Z[np.argpartition(-Z,n)[:n]]) 1367 | 1368 | < q90 1369 | Given an arbitrary number of vectors, build the cartesian product (every combination of every item) (★★★) 1370 | 1371 | < h90 1372 | hint: np.indices 1373 | 1374 | < a90 1375 | # Author: Stefan Van der Walt 1376 | 1377 | def cartesian(arrays): 1378 | arrays = [np.asarray(a) for a in arrays] 1379 | shape = (len(x) for x in arrays) 1380 | 1381 | ix = np.indices(shape, dtype=int) 1382 | ix = ix.reshape(len(arrays), -1).T 1383 | 1384 | for n, arr in enumerate(arrays): 1385 | ix[:, n] = arrays[n][ix[:, n]] 1386 | 1387 | return ix 1388 | 1389 | print (cartesian(([1, 2, 3], [4, 5], [6, 7]))) 1390 | 1391 | < q91 1392 | How to create a record array from a regular array? (★★★) 1393 | 1394 | < h91 1395 | hint: np.core.records.fromarrays 1396 | 1397 | < a91 1398 | Z = np.array([("Hello", 2.5, 3), 1399 | ("World", 3.6, 2)]) 1400 | R = np.core.records.fromarrays(Z.T, 1401 | names='col1, col2, col3', 1402 | formats = 'S8, f8, i8') 1403 | print(R) 1404 | 1405 | < q92 1406 | Consider a large vector Z, compute Z to the power of 3 using 3 different methods (★★★) 1407 | 1408 | < h92 1409 | hint: np.power, *, np.einsum 1410 | 1411 | < a92 1412 | # Author: Ryan G. 1413 | 1414 | x = np.random.rand(int(5e7)) 1415 | 1416 | %timeit np.power(x,3) 1417 | %timeit x*x*x 1418 | %timeit np.einsum('i,i,i->i',x,x,x) 1419 | 1420 | < q93 1421 | 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? (★★★) 1422 | 1423 | < h93 1424 | hint: np.where 1425 | 1426 | < a93 1427 | # Author: Gabe Schwartz 1428 | 1429 | A = np.random.randint(0,5,(8,3)) 1430 | B = np.random.randint(0,5,(2,2)) 1431 | 1432 | C = (A[..., np.newaxis, np.newaxis] == B) 1433 | rows = np.where(C.any((3,1)).all(1))[0] 1434 | print(rows) 1435 | 1436 | < q94 1437 | Considering a 10x3 matrix, extract rows with unequal values (e.g. [2,2,3]) (★★★) 1438 | 1439 | < h94 1440 | No hints provided... 1441 | 1442 | < a94 1443 | # Author: Robert Kern 1444 | 1445 | Z = np.random.randint(0,5,(10,3)) 1446 | print(Z) 1447 | # solution for arrays of all dtypes (including string arrays and record arrays) 1448 | E = np.all(Z[:,1:] == Z[:,:-1], axis=1) 1449 | U = Z[~E] 1450 | print(U) 1451 | # soluiton for numerical arrays only, will work for any number of columns in Z 1452 | U = Z[Z.max(axis=1) != Z.min(axis=1),:] 1453 | print(U) 1454 | 1455 | < q95 1456 | Convert a vector of ints into a matrix binary representation (★★★) 1457 | 1458 | < h95 1459 | hint: np.unpackbits 1460 | 1461 | < a95 1462 | # Author: Warren Weckesser 1463 | 1464 | I = np.array([0, 1, 2, 3, 15, 16, 32, 64, 128]) 1465 | B = ((I.reshape(-1,1) & (2**np.arange(8))) != 0).astype(int) 1466 | print(B[:,::-1]) 1467 | 1468 | # Author: Daniel T. McDonald 1469 | 1470 | I = np.array([0, 1, 2, 3, 15, 16, 32, 64, 128], dtype=np.uint8) 1471 | print(np.unpackbits(I[:, np.newaxis], axis=1)) 1472 | 1473 | < q96 1474 | Given a two dimensional array, how to extract unique rows? (★★★) 1475 | 1476 | < h96 1477 | hint: np.ascontiguousarray | np.unique 1478 | 1479 | < a96 1480 | # Author: Jaime Fernández del Río 1481 | 1482 | Z = np.random.randint(0,2,(6,3)) 1483 | T = np.ascontiguousarray(Z).view(np.dtype((np.void, Z.dtype.itemsize * Z.shape[1]))) 1484 | _, idx = np.unique(T, return_index=True) 1485 | uZ = Z[idx] 1486 | print(uZ) 1487 | 1488 | # Author: Andreas Kouzelis 1489 | # NumPy >= 1.13 1490 | uZ = np.unique(Z, axis=0) 1491 | print(uZ) 1492 | 1493 | < q97 1494 | Considering 2 vectors A & B, write the einsum equivalent of inner, outer, sum, and mul function (★★★) 1495 | 1496 | < h97 1497 | hint: np.einsum 1498 | 1499 | < a97 1500 | # Author: Alex Riley 1501 | # Make sure to read: http://ajcr.net/Basic-guide-to-einsum/ 1502 | 1503 | A = np.random.uniform(0,1,10) 1504 | B = np.random.uniform(0,1,10) 1505 | 1506 | np.einsum('i->', A) # np.sum(A) 1507 | np.einsum('i,i->i', A, B) # A * B 1508 | np.einsum('i,i', A, B) # np.inner(A, B) 1509 | np.einsum('i,j->ij', A, B) # np.outer(A, B) 1510 | 1511 | < q98 1512 | Considering a path described by two vectors (X,Y), how to sample it using equidistant samples (★★★)? 1513 | 1514 | < h98 1515 | hint: np.cumsum, np.interp 1516 | 1517 | < a98 1518 | # Author: Bas Swinckels 1519 | 1520 | phi = np.arange(0, 10*np.pi, 0.1) 1521 | a = 1 1522 | x = a*phi*np.cos(phi) 1523 | y = a*phi*np.sin(phi) 1524 | 1525 | dr = (np.diff(x)**2 + np.diff(y)**2)**.5 # segment lengths 1526 | r = np.zeros_like(x) 1527 | r[1:] = np.cumsum(dr) # integrate path 1528 | r_int = np.linspace(0, r.max(), 200) # regular spaced path 1529 | x_int = np.interp(r_int, r, x) # integrate path 1530 | y_int = np.interp(r_int, r, y) 1531 | 1532 | < q99 1533 | 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. (★★★) 1534 | 1535 | < h99 1536 | hint: np.logical_and.reduce, np.mod 1537 | 1538 | < a99 1539 | # Author: Evgeni Burovski 1540 | 1541 | X = np.asarray([[1.0, 0.0, 3.0, 8.0], 1542 | [2.0, 0.0, 1.0, 1.0], 1543 | [1.5, 2.5, 1.0, 0.0]]) 1544 | n = 4 1545 | M = np.logical_and.reduce(np.mod(X, 1) == 0, axis=-1) 1546 | M &= (X.sum(axis=-1) == n) 1547 | print(X[M]) 1548 | 1549 | < q100 1550 | 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). (★★★) 1551 | 1552 | < h100 1553 | hint: np.percentile 1554 | 1555 | < a100 1556 | # Author: Jessica B. Hamrick 1557 | 1558 | X = np.random.randn(100) # random 1D array 1559 | N = 1000 # number of bootstrap samples 1560 | idx = np.random.randint(0, X.size, (N, X.size)) 1561 | means = X[idx].mean(axis=1) 1562 | confint = np.percentile(means, [2.5, 97.5]) 1563 | print(confint) 1564 | -------------------------------------------------------------------------------- /source/headers.ktx: -------------------------------------------------------------------------------- 1 | < header 2 | # 100 numpy exercises 3 | 4 | This is a collection of exercises that have been collected in the numpy mailing list, on stack overflow 5 | and in the numpy documentation. The goal of this collection is to offer a quick reference for both old 6 | and new users but also to provide a set of exercises for those who teach. 7 | 8 | 9 | If you find an error or think you've a better way to solve some of them, feel 10 | free to open an issue at . 11 | 12 | 13 | < sub_header 14 | File automatically generated. See the documentation to update questions/answers/hints programmatically. 15 | 16 | 17 | < jupyter_instruction 18 | Run the `initialize.py` module, then for each question you can query the 19 | answer or an hint with `hint(n)` or `answer(n)` for `n` question number. 20 | 21 | 22 | < jupyter_instruction_rand 23 | Run the `initialize.py` module, then call a random question with `pick()` an hint towards its solution with 24 | `hint(n)` and the answer with `answer(n)`, where n is the number of the picked question. 25 | 26 | --------------------------------------------------------------------------------