100 numpy exercises (with solutions)

Overview

100 numpy exercises

Binder

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.

Test them on Binder
Read them on GitHub

Note: markdown and ipython notebook are created programmatically from the source data in source/exercises.ktx. To modify the content of these files, please change the text in the source and run the generators.py module with a python interpreter with the libraries under requirements.txt installed.

The keyed text format (ktx) is a minimal human readable key-values to store text (markdown or others) indexed by keys.

This work is licensed under the MIT license.
DOI

Comments
  • Programmatically create markdown and jupyter notebook from a share dictionary with questions and answers

    Programmatically create markdown and jupyter notebook from a share dictionary with questions and answers

    Over the past months I had found numpy 100 very handy for learning, and as a source of information.

    At the same time it is not ideally implemented. If a question or answer needs an updated, this must be done manually in all files involved.

    To solve this issue I had embedded headers, questions, hints and answer in a python file as strings and dictionaries and created a method to automatically generate the jupyter notebooks and the markdown files.

    Changing the source dictionaries and stings would change the output files.

    E.g: if a question needs update, just update it under -data_source.py- source/questions.ktx and then re-create all the files with the updated questions with:

    python generators.py
    

    Also, there is no more need to have several jupyter notebooks, since hints and answers can be queried programmatically with hint(n) and answer(n) from within the jupyter notebook.

    A jupyter notebook where to query a random question (flashcard style) had been added too.

    Pleaese note: binder and link in the readme may need to be updated, to keep the binder version in sync with the current repo!

    After merging the repo would look like: https://github.com/SebastianoF/numpy-100/tree/dev

    opened by SebastianoF 10
  • 27. round away from 0 solution is wrong

    27. round away from 0 solution is wrong

    trunc() should be round(), like this: print (np.round(Z + np.copysign(0.5, Z)))

    Example: an original value of 1.4 becomes 1.9, which then rounds to 2 (correct) or truncates to 1 (incorrect).

    Alternatively, this might be more readable, but maybe it teaches less. Maybe having multiple solutions for each problem would be most educational?

    Z[Z<0] = np.floor(Z[Z<0])
    Z[Z>0] = np.ceil(Z[Z>0])
    print (Z)
    
    opened by MarredCheese 8
  • An alternative solution for Q.76

    An alternative solution for Q.76

    1. 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]) (★★★) hint: from numpy.lib import stride_tricks

    # Author: Joe Kington / Erik Rigtorp from numpy.lib import stride_tricks

    def rolling(a, window): shape = (a.size - window + 1, window) strides = (a.strides[0], a.strides[0]) return stride_tricks.as_strided(a, shape=shape, strides=strides) Z = rolling(np.arange(10), 3) print(Z)

    Same as the last issue, sliding_window_view is an easier function in NumPy. The new solution will be:

    Z = np.arange(10)
    print(sliding_window_view(Z, window_shape=(3)))
    
    opened by iamyifan 7
  • Separate wording from solution

    Separate wording from solution

    Hi !

    Very nice set of exercice, I am walking through it ! It would be nice to be able to scroll without the fear of seeing the answer and to do exercices in any order.

    Kind regards

    opened by lcetinsoy 7
  • A doubt about question No.74

    A doubt about question No.74

    1. Given an array C that is a bincount, how to produce an array A such that np.bincount(A) == C? (★★★)

    The given answer is shown as below. C = np.bincount([1,1,2,3,4,4,6]) A = np.repeat(np.arange(len(C)), C) print(A)

    There maybe a problem with the description of question No.74,the answer given can only solve the problem of Non-strictly increasing 1-d array not for all kind of 1-d array.

    opened by madeirak 6
  • 20 - solution returns index of 101st element

    20 - solution returns index of 101st element

    In question 20, it is assumed that the 100th element is at index 100, which is inconsistent with question 6, where the 5th element is assumed to be at index 4.

    opened by greenovid 6
  • Alternative solution  for 87.

    Alternative solution for 87.

    Numpy has (finally) "upstreamed" skimage's view_as_windows under the name sliding_window_view. With this we can write exercise 87 using more ~verbose~ clear syntax

    Z = np.ones((16,16))
    k = 4
    
    windows = np.lib.stride_tricks.sliding_window_view(Z, (k, k))
    relevant_windows = windows[::k, ::k, ...]
    S = np.sum(np.sum(relevant_windows, axis=-1), axis=-1)
    

    or if we prefer (potentially hard to maintain) one-liners

    Z = np.ones((16,16))
    k = 4
    
    S = np.sum(
        np.sum(
            np.lib.stride_tricks.sliding_window_view(Z, (k, k))[::k, ::k, ...]
            axis=-1), 
        axis=-1)
    
    opened by FirefoxMetzger 5
  • rougier/numpy-100 exercise - Que 16. alternate solution

    rougier/numpy-100 exercise - Que 16. alternate solution

    1. How to add a border (filled with 0's) around an existing array? (★☆☆)¶

    Proposed Solution -

    a=np.random.randint(1,10,(5,5)) print(a) a[0:,(0,-1)]=0 a[(0,-1),1:-1]=0 print(a)

    Pl. give feedback on this, I am new to Python.

    opened by sudhendra-github 5
  • Solution to

    Solution to "How to find rows of A that contain elements of each row of B" exercise

    Hi, It seems the solution given is wrong unless I misunderstood the question. The question is:

    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?

    The solution provided selects rows of A that contain (1) at least two unique elements of B (can be the same unique element of B repeated twice) or (2) at least one element that occurs 2 or more times in B. The rows of B are irrelevant. This seems not to answer the question correctly. Example:

    B = np.array([[0,1],[2,2]])
    A = np.array([[3,3,3],[0,1,3],[0,0,3],[1,1,3],[2,3,3],[0,2,3],[1,2,3]])
    

    The correct solution should pick rows of A that contains 0 and 2 or 1 and 2 (i.e. each row of B is represented in a given row of A) - so only rows 5 an 6. Current solution will also pick rows of A that contain [0,1], 2x 0, 2x 1 or 1x 2 - so rows 1,2,3,4.

    C = (A[..., np.newaxis, np.newaxis] == B)
    rows = (C.sum(axis=(1,2,3)) >= B.shape[1]).nonzero()[0]
    print(rows)
    
    [1 2 3 4 5 6]
    

    The correct solution could be:

    C = (A[..., np.newaxis, np.newaxis] == B)
    rows = np.where(C.any((3,1)).all(1))[0]
    print(rows)
    
    [5 6]
    
    opened by ibah 5
  • Fail to load the ipython notebook

    Fail to load the ipython notebook

    Hi, I got something wrong with the ipython notebook in Binder.

    what I got: 2016-08-31 22 13 31

    and when I opened the 100 numpy exercises.ipynb file with my ipython I got the same error. my ipython version: 4.2.1

    opened by robeatnik 5
  • Answer 81 improved - no stride_tricks, just numpy

    Answer 81 improved - no stride_tricks, just numpy

    I suggest to use an answer that is done only by numpy means. stride_tricks is defined elsewhere, it is less elegant and may confuse the user. Pls consider my proposed solution.

    opened by poedator 4
  • About question 19

    About question 19

    the alternative solution does not work for creating a checkerboard pattern.

    # Alternative solution: Using reshaping
    arr = np.ones(64,dtype=int)
    arr[::2]=0
    arr = arr.reshape((8,8))
    print(arr)
    

    this will be the output. [[0 1 0 1 0 1 0 1] [0 1 0 1 0 1 0 1] [0 1 0 1 0 1 0 1] [0 1 0 1 0 1 0 1] [0 1 0 1 0 1 0 1] [0 1 0 1 0 1 0 1] [0 1 0 1 0 1 0 1] [0 1 0 1 0 1 0 1]]

    But what we want is

    Z = np.zeros((8,8),dtype=int)
    Z[1::2,::2] = 1
    Z[::2,1::2] = 1
    print(Z)
    

    [[0 1 0 1 0 1 0 1] [1 0 1 0 1 0 1 0] [0 1 0 1 0 1 0 1] [1 0 1 0 1 0 1 0] [0 1 0 1 0 1 0 1] [1 0 1 0 1 0 1 0] [0 1 0 1 0 1 0 1] [1 0 1 0 1 0 1 0]]

    or

    z = np.zeros((8, 8), int)
    z[1::2, 1::2] = 1
    z[::2, ::2] = 1
    print(z)
    

    [[1 0 1 0 1 0 1 0] [0 1 0 1 0 1 0 1] [1 0 1 0 1 0 1 0] [0 1 0 1 0 1 0 1] [1 0 1 0 1 0 1 0] [0 1 0 1 0 1 0 1] [1 0 1 0 1 0 1 0] [0 1 0 1 0 1 0 1]]

    opened by hacshyac 1
  • Possibly Faster solution for #66

    Possibly Faster solution for #66

    I thought maybe using .view() may be faster. And it seems.

    w, h = 256,256
    
    l = np.random.randint(0,4,(h,w,3), dtype=np.uint8)
    l2 = np.zeros((h,w,4), dtype=np.uint8)
    l2[...,:3]=l[...,:3]
    l2[...,3] = l2[...,2]
    l3 = l2.view(dtype=np.int32)
    n= len(np.unique(l3))
    print(n)
    

    My %%timeit shows 2.68 ms ± 67.1 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) compared to Mark Setchell's version 4 ms ± 259 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) I think there might be some trade off between allocating new memory and using view.

    The solution utilizes the fact that using .view() we can simply use np.unique(, axis=None). Since color is composed of 3bytes I just copied the last byte and did 4-bytes comparison with .view(dtype=np.int32)

    opened by kwhkim 8
  • Q16 fancy indexing solution does not work

    Q16 fancy indexing solution does not work

    An example:

    >>> a = np.random.randint(0, 10, (3, 3))
    >>> a[:, [0, -1]] = 0
    >>> a[[0, -1], :] = 0
    >>> a
    array([[0, 0, 0],
           [0, 5, 0],
           [0, 0, 0]])
    

    Unless I'm understanding the question incorrectly here (but the np.pad solution is doing what I first expected), the fancy indexing solution does not work.

    opened by Objectivitix 1
  • Problem with initialise.py

    Problem with initialise.py

    Hey guys,

    I was going to start doing a bunch of exercises about numpy and to start I had to run the first cell. I appears to be an error with that. I am new with github. I would be happy if you could help me :) Below, I sent the screenshot duv1

    opened by 6oncv1o 1
Releases(1.1)
Owner
Nicolas P. Rougier
Researcher in computational and cognitive neuroscience supporting open source, open access and open science.
Nicolas P. Rougier
Build documentation in multiple repos into one site.

mkdocs-multirepo-plugin Build documentation in multiple repos into one site. Setup Install plugin using pip: pip install git+https://github.com/jdoiro

Joseph Doiron 47 Dec 28, 2022
More detailed upload statistics for Nicotine+

More Upload Statistics A small plugin for Nicotine+ 3.1+ to create more detailed upload statistics. ⚠ No data previous to enabling this plugin will be

Nick 1 Dec 17, 2021
Generate YARA rules for OOXML documents using ZIP local header metadata.

apooxml Generate YARA rules for OOXML documents using ZIP local header metadata. To learn more about this tool and the methodology behind it, check ou

MANDIANT 34 Jan 26, 2022
Test utility for validating OpenAPI documentation

DRF OpenAPI Tester This is a test utility to validate DRF Test Responses against OpenAPI 2 and 3 schema. It has built-in support for: OpenAPI 2/3 yaml

snok 106 Jan 05, 2023
SqlAlchemy Flask-Restful Swagger Json:API OpenAPI

SAFRS: Python OpenAPI & JSON:API Framework Overview Installation JSON:API Interface Resource Objects Relationships Methods Custom Methods Class Method

Thomas Pollet 361 Nov 16, 2022
Explorative Data Analysis Guidelines

Explorative Data Analysis Get data into a usable format! Find out if the following predictive modeling phase will be successful! Combine everything in

Florian Rohrer 18 Dec 26, 2022
Sphinx theme for readthedocs.org

Read the Docs Sphinx Theme This Sphinx theme was designed to provide a great reader experience for documentation users on both desktop and mobile devi

Read the Docs 4.3k Dec 31, 2022
Literate-style documentation generator.

888888b. 888 Y88b 888 888 888 d88P 888 888 .d8888b .d8888b .d88b. 8888888P" 888 888 d88P" d88P" d88""88b 888 888 888

Pycco 808 Dec 27, 2022
A simple document management REST based API for collaboratively interacting with documents

documan_api A simple document management REST based API for collaboratively interacting with documents.

Shahid Yousuf 1 Jan 22, 2022
Example Python code for running the mango-explorer marketmaker

🥭 Mango Explorer 📖 Introduction This guide will show you how to load and run a customisable marketmaker that runs on Mango Markets using the mango-e

Blockworks Foundation 2 Apr 11, 2022
charcade is a string manipulation library that can animate, color, and bruteforce strings

charcade charcade is a string manipulation library that can animate, color, and bruteforce strings. Features Animating text for CLI applications with

Aaron 8 May 23, 2022
Word document generator with python

In this study, real world data is anonymized. The content is completely different, but the structure is the same. It was a script I prepared for the backend of a work using UiPath.

Ezgi Turalı 3 Jan 30, 2022
Some of the best ways and practices of doing code in Python!

Pythonicness ❤ This repository contains some of the best ways and practices of doing code in Python! Features Properly formatted codes (PEP 8) for bet

Samyak Jain 2 Jan 15, 2022
ReStructuredText and Sphinx bridge to Doxygen

Breathe Packagers: PGP signing key changes for Breathe = v4.23.0. https://github.com/michaeljones/breathe/issues/591 This is an extension to reStruct

Michael Jones 643 Dec 31, 2022
learn python in 100 days, a simple step could be follow from beginner to master of every aspect of python programming and project also include side project which you can use as demo project for your personal portfolio

learn python in 100 days, a simple step could be follow from beginner to master of every aspect of python programming and project also include side project which you can use as demo project for your

BDFD 6 Nov 05, 2022
Python syntax highlighted Markdown doctest.

phmdoctest 1.3.0 Introduction Python syntax highlighted Markdown doctest Command line program and Python library to test Python syntax highlighted cod

Mark Taylor 16 Aug 09, 2022
Preview title and other information about links sent to chats.

Link Preview A small plugin for Nicotine+ to display preview information like title and description about links sent in chats. Plugin created with Nic

Nick 0 Sep 05, 2021
A curated list of awesome mathematics resources

A curated list of awesome mathematics resources

Cyrille Rossant 6.7k Jan 05, 2023
MonsterManualPlus - An advanced monster manual for Tower of the Sorcerer.

Monster Manual + This is an advanced monster manual for Tower of the Sorcerer mods. Users can get a plenty of extra imformation for decision making wh

Yifan Zhou 1 Jan 01, 2022
The blazing-fast Discord bot.

Wavy Wavy is an open-source multipurpose Discord bot built with pycord. Wavy is still in development, so use it at your own risk. Tools and services u

Wavy 7 Dec 27, 2022