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
step by step guide for beginners for getting started with open source

Step-by-Step Guide for beginners for getting started with Open-Source Here The Contribution Begins 💻 If you are a beginner then this repository is fo

Arpit Jain 66 Jan 03, 2023
Code for our SIGIR 2022 accepted paper : P3 Ranker: Mitigating the Gaps between Pre-training and Ranking Fine-tuning with Prompt-based Learning and Pre-finetuning

P3 Ranker Implementation for our SIGIR2022 accepted paper: P3 Ranker: Mitigating the Gaps between Pre-training and Ranking Fine-tuning with Prompt-bas

14 Jan 04, 2023
This contains timezone mapping information for when preprocessed from the geonames data

when-data This contains timezone mapping information for when preprocessed from the geonames data. It exists in a separate repository so that one does

Armin Ronacher 2 Dec 07, 2021
Members: Thomas Longuevergne Program: Network Security Course: 1DV501 Date of submission: 2021-11-02

Mini-project report Members: Thomas Longuevergne Program: Network Security Course: 1DV501 Date of submission: 2021-11-02 Introduction This project was

1 Nov 08, 2021
Your Project with Great Documentation.

Read Latest Documentation - Browse GitHub Code Repository The only thing worse than documentation never written, is documentation written but never di

Timothy Edmund Crosley 809 Dec 28, 2022
Assignments from Launch X's python introduction course

Launch X - On Boarding Assignments from Launch X's Python Introduction Course Explore the docs » Report Bug · Request Feature Table of Contents About

Javier Méndez 0 Mar 15, 2022
🏆 A ranked list of awesome python developer tools and libraries. Updated weekly.

Best-of Python Developer Tools 🏆 A ranked list of awesome python developer tools and libraries. Updated weekly. This curated list contains 250 awesom

Machine Learning Tooling 646 Jan 07, 2023
Seamlessly integrate pydantic models in your Sphinx documentation.

Seamlessly integrate pydantic models in your Sphinx documentation.

Franz Wöllert 71 Dec 26, 2022
epub2sphinx is a tool to convert epub files to ReST for Sphinx

epub2sphinx epub2sphinx is a tool to convert epub files to ReST for Sphinx. It uses Pandoc for converting HTML data inside epub files into ReST. It cr

Nihaal 8 Dec 15, 2022
Data Inspector is an open-source python library that brings 15++ types of different functions to make EDA, data cleaning easier.

Data Inspector Data Inspector is an open-source python library that brings 15 types of different functions to make EDA, data cleaning easier. Author:

Kazi Amit Hasan 38 Nov 24, 2022
Demonstration that AWS IAM policy evaluation docs are incorrect

The flowchart from the AWS IAM policy evaluation documentation page, as of 2021-09-12, and dating back to at least 2018-12-27, is the following: The f

Ben Kehoe 15 Oct 21, 2022
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
Markdown documentation generator from Google docstrings

mkgendocs A Python package for automatically generating documentation pages in markdown for Python source files by parsing Google style docstring. The

Davide Nunes 44 Dec 18, 2022
Explain yourself! Interrogate a codebase for docstring coverage.

interrogate: explain yourself Interrogate a codebase for docstring coverage. Why Do I Need This? interrogate checks your code base for missing docstri

Lynn Root 435 Dec 29, 2022
JMESPath is a query language for JSON.

JMESPath JMESPath (pronounced "james path") allows you to declaratively specify how to extract elements from a JSON document. For example, given this

1.7k Dec 31, 2022
A curated list of awesome tools for Sphinx Python Documentation Generator

Awesome Sphinx (Python Documentation Generator) A curated list of awesome extra libraries, software and resources for Sphinx (Python Documentation Gen

Hyunjun Kim 831 Dec 27, 2022
Mayan EDMS is a document management system.

Mayan EDMS is a document management system. Its main purpose is to store, introspect, and categorize files, with a strong emphasis on preserving the contextual and business information of documents.

3 Oct 02, 2021
:blue_book: Automatic documentation from sources, for MkDocs.

mkdocstrings Automatic documentation from sources, for MkDocs. Features - Python handler - Requirements - Installation - Quick usage Features Language

1.1k Jan 04, 2023
FireEye Related Projects

FireEye FireEye Related Projects Tor-IP-Collector Simple python script that will collect a list of TOR IPs from the SecOps Institute Github and inject

Taran Ulrich 2 Nov 12, 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