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
This is a repository for "100 days of code challenge" projects. You can reach all projects from beginner to professional which are written in Python.

100 Days of Code It's a challenge that aims to gain code practice and enhance programming knowledge. Day #1 Create a Band Name Generator It's actually

SelenNB 2 May 12, 2022
CoderByte | Practice, Tutorials & Interview Preparation Solutions|

CoderByte | Practice, Tutorials & Interview Preparation Solutions This repository consists of solutions to CoderByte practice, tutorials, and intervie

Eda AYDIN 6 Aug 9, 2022
Numpy's Sphinx extensions

numpydoc -- Numpy's Sphinx extensions This package provides the numpydoc Sphinx extension for handling docstrings formatted according to the NumPy doc

NumPy 234 Dec 26, 2022
Python Advanced --- numpy, decorators, networking

Python Advanced --- numpy, decorators, networking (and more?) Hello everyone ?? This is the project repo for the "Python Advanced - ..." introductory

Andreas Poehlmann 2 Nov 5, 2021
Experimental solutions to selected exercises from the book [Advances in Financial Machine Learning by Marcos Lopez De Prado]

Advances in Financial Machine Learning Exercises Experimental solutions to selected exercises from the book Advances in Financial Machine Learning by

Brian 1.4k Jan 4, 2023
Composable transformations of Python+NumPy programsComposable transformations of Python+NumPy programs

Chex Chex is a library of utilities for helping to write reliable JAX code. This includes utils to help: Instrument your code (e.g. assertions) Debug

DeepMind 506 Jan 8, 2023
MLP-Numpy - A simple modular implementation of Multi Layer Perceptron in pure Numpy.

MLP-Numpy A simple modular implementation of Multi Layer Perceptron in pure Numpy. I used the Iris dataset from scikit-learn library for the experimen

Soroush Omranpour 1 Jan 1, 2022
A repo with study material, exercises, examples, etc for Devnet SPAUTO

MPLS in the SDN Era --> DevNet SPAUTO Get right to the study material: Checkout the Wiki! A lab topology based on MPLS in the SDN era book used for 30

Hugo Tinoco 67 Nov 16, 2022
Automation for grabbing keys from a Linux host. Useful during red team exercises to quickly help assess what access to a Linux host can lead to.

keygrabber Automation for grabbing keys from a Linux host. This can be helpful during red team exercises when you gain access to a Linux host and want

Cedric Owens 14 Sep 27, 2022
A collection of python exercises to help your learning path!

How to use Step 1: run this command git clone https://github.com/TechPenguineer/Python-Exercises.git Step 2: Run this command cd Python-Exercises You

Tech Penguin 5 Aug 5, 2021
Exercism exercises in Python.

Exercism exercises in Python.

Exercism 1.3k Jan 4, 2023
Small exercises to get you used to reading and writing Python code!

Pythonlings Welcome to Pythonlings, an automated Python tutorial program (inspired by Rustlings and Haskellings). WIP This program is still working in

鹤翔万里 5 Sep 23, 2022
LibreMind is a free meditation app made in under 24 hours. It has various meditation, breathwork, and visualization exercises.

libreMind Meditation exercises What is it? LibreMind is a free meditation app made in under 24 hours. It has various meditation, breathwork, and visua

null 1 May 24, 2022
Speed up your typing by some exercises in the multi-platform(Windows/Ubuntu).

Introduction This project purpose is speed up your typing by some exercises in the multi-platform(Windows/Ubuntu). Build Environment Software Environm

lyfer233 1 Mar 24, 2022
image-processing exercises.

image_processing Assignment 21 Checkered Board Create a chess table using numpy and opencv. view: Color Correction Reverse black and white colors with

Benyamin Zojaji 25 Dec 15, 2022
Coursera learning course Python the basics. Programming exercises and tasks

HSE_Python_the_basics Welcome to BAsics programming Python! You’re joining thousands of learners currently enrolled in the course. I'm excited to have

PavelRyzhkov 0 Jan 5, 2022
Study German declensions (dER nettE Mann, ein nettER Mann, mit dEM nettEN Mann, ohne dEN nettEN Mann ...) Generate as many exercises as you want using the incredible power of SPACY!

Study German declensions (dER nettE Mann, ein nettER Mann, mit dEM nettEN Mann, ohne dEN nettEN Mann ...) Generate as many exercises as you want using the incredible power of SPACY!

Hans Alemão 4 Jul 20, 2022
A repo with study material, exercises, examples, etc for Devnet SPAUTO

MPLS in the SDN Era --> DevNet SPAUTO All of the study notes have now been moved to use auto-generated documentation to build a static site with Githu

Hugo Tinoco 67 Nov 16, 2022
Program created with opencv that allows you to automatically count your repetitions on several fitness exercises.

Virtual partner of gym Description Program created with opencv that allows you to automatically count your repetitions on several fitness exercises li

null 1 Jan 4, 2022
All exercises done during the Python 3 course in the Video Course (World 1, 2 and 3)

Python3-cursoemvideo-exercises - All exercises done during the Python 3 course in the Video Course (World 1, 2 and 3)

Renan Barbosa 3 Jan 17, 2022