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
Code and pre-trained models for "ReasonBert: Pre-trained to Reason with Distant Supervision", EMNLP'2021

ReasonBERT Code and pre-trained models for ReasonBert: Pre-trained to Reason with Distant Supervision, EMNLP'2021 Pretrained Models The pretrained mod

SunLab-OSU 29 Dec 19, 2022
A Sublime Text plugin to select a default syntax dialect

Default Syntax Chooser This Sublime Text 4 plugin provides the set_default_syntax_dialect command. This command manipulates a syntax file (e.g.: SQL.s

3 Jan 14, 2022
A curated list of awesome mathematics resources

A curated list of awesome mathematics resources

Cyrille Rossant 6.7k Jan 05, 2023
🌱 Complete API wrapper of Seedr.cc

Python API Wrapper of Seedr.cc Table of Contents Installation How I got the API endpoints? Start Guide Getting Token Logging with Username and Passwor

Hemanta Pokharel 43 Dec 26, 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 next-generation curated knowledge sharing platform for data scientists and other technical professions.

Knowledge Repo The Knowledge Repo project is focused on facilitating the sharing of knowledge between data scientists and other technical roles using

Airbnb 5.2k Dec 27, 2022
Plugins for MkDocs.

Plugins for MkDocs and Python Markdown pip install neoteroi-mkdocs This package includes the following plugins and extensions: Name Description Type m

35 Dec 23, 2022
level2-data-annotation_cv-level2-cv-15 created by GitHub Classroom

[AI Tech 3기 Level2 P Stage] 글자 검출 대회 팀원 소개 김규리_T3016 박정현_T3094 석진혁_T3109 손정균_T3111 이현진_T3174 임종현_T3182 Overview OCR (Optimal Character Recognition) 기술

6 Jun 10, 2022
A collection of lecture notes, drawings, flash cards, mind maps, scripts

Neuroanatomy A collection of lecture notes, drawings, flash cards, mind maps, scripts and other helpful resources for the course "Functional Organizat

Georg Reich 3 Sep 21, 2022
Course materials for: Geospatial Data Science

Course materials for: Geospatial Data Science These course materials cover the lectures for the course held for the first time in spring 2022 at IT Un

Michael Szell 266 Jan 02, 2023
Documentation for the lottie file format

Lottie Documentation This repository contains both human-readable and machine-readable documentation about the Lottie format The documentation is avai

LottieFiles 25 Jan 05, 2023
NoVmpy - NoVmpy with python

git clone -b dev-1 https://github.com/wallds/VTIL-Python.git cd VTIL-Python py s

263 Dec 23, 2022
LotteryBuyPredictionWebApp - Lottery Purchase Prediction Model

Lottery Purchase Prediction Model Objective and Goal Predict the lottery type th

Wanxuan Zhang 2 Feb 14, 2022
Python 3 wrapper for the Vultr API v2.0

Vultr Python Python wrapper for the Vultr API. https://www.vultr.com https://www.vultr.com/api This is currently a WIP and not complete, but has some

CSSNR 6 Apr 28, 2022
Contains the assignments from the course Building a Modern Computer from First Principles: From Nand to Tetris.

Contains the assignments from the course Building a Modern Computer from First Principles: From Nand to Tetris.

Matheus Rodrigues 1 Jan 20, 2022
swagger-codegen contains a template-driven engine to generate documentation, API clients and server stubs in different languages by parsing your OpenAPI / Swagger definition.

Master (2.4.25-SNAPSHOT): 3.0.31-SNAPSHOT: Maven Central ⭐ ⭐ ⭐ If you would like to contribute, please refer to guidelines and a list of open tasks. ⭐

Swagger 15.2k Dec 31, 2022
Speed up Sphinx builds by selectively removing toctrees from some pages

Remove toctrees from Sphinx pages Improve your Sphinx build time by selectively removing TocTree objects from pages. This is useful if your documentat

Executable Books 8 Jan 04, 2023
This is the repository that includes the code material for the ESweek 2021 for the Education Class Lecture A3 "Learn to Drive (and Race!) Autonomous Vehicles"

ESweek2021_educationclassA3 This is the repository that includes the code material for the ESweek 2021 for the Education Class Lecture A3 "Learn to Dr

F1TENTH Autonomous Racing Community 29 Dec 06, 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
Generates, filters, parses, and cleans data regarding the financial disclosures of judges in the American Judicial System

This repository contains code that gets data regarding financial disclosures from the Court Listener API main.py: contains driver code that interacts

Ali Rastegar 2 Aug 06, 2022