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
Python Deep Dive Course - Accompanying Materials

Python Deep Dive Various Jupyter notebooks and Python sources associated with my Udemy Python 3 Deep Dive course series: Part 1: Mainly functional pro

Fred Baptiste 1.1k Dec 30, 2022
Mkdocs obsidian publish - Publish your obsidian vault through a python script

Mkdocs Obsidian Mkdocs Obsidian is an association between a python script and a

Mara 49 Jan 09, 2023
Fun interactive program to sort a list :)

LHD-Build-Sort-a-list Fun interactive program to sort a list :) Inspiration LHD Build Write a script to sort a list. What it does It is a menu driven

Ananya Gupta 1 Jan 15, 2022
VSCode extension that generates docstrings for python files

VSCode Python Docstring Generator Visual Studio Code extension to quickly generate docstrings for python functions. Features Quickly generate a docstr

Nils Werner 506 Jan 03, 2023
Credit EDA Case Study Using Python

This case study aims to identify patterns which indicate if a client has difficulty paying their installments which may be used for taking actions such as denying the loan, reducing the amount of loa

Purvi Padliya 1 Jan 14, 2022
python package sphinx template

python-package-sphinx-template python-package-sphinx-template

Soumil Nitin Shah 2 Dec 26, 2022
Always know what to expect from your data.

Great Expectations Always know what to expect from your data. Introduction Great Expectations helps data teams eliminate pipeline debt, through data t

Great Expectations 7.8k Jan 05, 2023
[Unofficial] Python PEP in EPUB format

PEPs in EPUB format This is a unofficial repository where I stock all valid PEPs in the EPUB format. Repository Cloning git clone --recursive Mickaël Schoentgen 9 Oct 12, 2022

30 Days of google cloud leaderboard website

30 Days of Cloud Leaderboard This is a leaderboard for the students of Thapar, Patiala who are participating in the 2021 30 days of Google Cloud Platf

Developer Student Clubs TIET 13 Aug 25, 2022
Create Python API documentation in Markdown format.

Pydoc-Markdown Pydoc-Markdown is a tool and library to create Python API documentation in Markdown format based on lib2to3, allowing it to parse your

Niklas Rosenstein 375 Jan 05, 2023
Jupyter Notebooks as Markdown Documents, Julia, Python or R scripts

Have you always wished Jupyter notebooks were plain text documents? Wished you could edit them in your favorite IDE? And get clear and meaningful diff

Marc Wouts 5.7k Jan 04, 2023
:blue_book: Automatic documentation from sources, for MkDocs.

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

Timothée Mazzucotelli 1.1k Dec 31, 2022
Some custom tweaks to the results produced by pytkdocs.

pytkdocs_tweaks Some custom tweaks for pytkdocs. For use as part of the documentation-generation-for-Python stack that comprises mkdocs, mkdocs-materi

Patrick Kidger 4 Nov 24, 2022
NetBox plugin that stores configuration diffs and checks templates compliance

Config Officer - NetBox plugin NetBox plugin that deals with Cisco device configuration (collects running config from Cisco devices, indicates config

77 Dec 21, 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 powerful Sphinx changelog-generating extension.

What is Releases? Releases is a Python (2.7, 3.4+) compatible Sphinx (1.8+) extension designed to help you keep a source control friendly, merge frien

Jeff Forcier 166 Dec 29, 2022
An introduction to hikari, complete with different examples for different command handlers.

An intro to hikari This repo provides some simple examples to get you started with hikari. Contained in this repo are bots designed with both the hika

Ethan Henderson 18 Nov 29, 2022
Use Brainf*ck with python!

Brainfudge Run Brainf*ck code with python! Classes Interpreter(array_len): encapsulate all functions into class __init__(self, array_len: int=30000) -

1 Dec 14, 2021
Collection of Summer 2022 tech internships!

Collection of Summer 2022 tech internships!

Pitt Computer Science Club (CSC) 15.6k Jan 03, 2023
Pystm32ai - A Python wrapper for the stm32ai command-line tool

PySTM32.AI A python wrapper for the stm32ai command-line tool to analyse deep le

Thibaut Vercueil 5 Jul 28, 2022