Removed sections to ease numbering

This commit is contained in:
Nicolas Rougier
2015-08-16 19:55:47 +02:00
parent 9d5189d5bd
commit 25ac81b95b
3 changed files with 190 additions and 264 deletions

View File

@@ -3,7 +3,7 @@
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head> <head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="Docutils 0.11: http://docutils.sourceforge.net/" /> <meta name="generator" content="Docutils 0.12: http://docutils.sourceforge.net/" />
<title>100 numpy exercises</title> <title>100 numpy exercises</title>
<link rel="stylesheet" href="numpy.css" type="text/css" /> <link rel="stylesheet" href="numpy.css" type="text/css" />
</head> </head>
@@ -27,17 +27,11 @@ is:</p>
</pre> </pre>
<p>Here is what the page looks like so far: <p>Here is what the page looks like so far:
<a class="reference external" href="http://www.labri.fr/perso/nrougier/teaching/numpy.100/index.html">http://www.labri.fr/perso/nrougier/teaching/numpy.100/index.html</a></p> <a class="reference external" href="http://www.labri.fr/perso/nrougier/teaching/numpy.100/index.html">http://www.labri.fr/perso/nrougier/teaching/numpy.100/index.html</a></p>
<div class="note">
<p class="first admonition-title">Note</p>
<p class="last">The level names came from an old-game (Dungeon Master)</p>
</div>
<p>Repository is at: <a class="reference external" href="https://github.com/rougier/numpy-100">https://github.com/rougier/numpy-100</a></p> <p>Repository is at: <a class="reference external" href="https://github.com/rougier/numpy-100">https://github.com/rougier/numpy-100</a></p>
<p>The corresponding <a class="reference external" href="https://github.com/rougier/numpy-100/blob/master/README.ipynb">IPython notebook</a> is available <p>The corresponding <a class="reference external" href="https://github.com/rougier/numpy-100/blob/master/README.ipynb">IPython notebook</a> is available
from the github repo, thanks to the <a class="reference external" href="https://github.com/esc/rst2ipynb">rst2ipynb</a> conversion tool by <a class="reference external" href="http://haenel.co">Valentin Haenel</a></p> from the github repo, thanks to the <a class="reference external" href="https://github.com/esc/rst2ipynb">rst2ipynb</a> conversion tool by <a class="reference external" href="http://haenel.co">Valentin Haenel</a></p>
<p>Thanks to Michiaki Ariga, there is now a <p>Thanks to Michiaki Ariga, there is now a
<a class="reference external" href="https://github.com/chezou/julia-100-exercises">Julia version</a>.</p> <a class="reference external" href="https://github.com/chezou/julia-100-exercises">Julia version</a>.</p>
<div class="section" id="neophyte">
<h1>Neophyte</h1>
<ol class="arabic"> <ol class="arabic">
<li><p class="first">Import the numpy package under the name <tt class="docutils literal">np</tt></p> <li><p class="first">Import the numpy package under the name <tt class="docutils literal">np</tt></p>
<pre class="code python literal-block"> <pre class="code python literal-block">
@@ -94,16 +88,13 @@ from the github repo, thanks to the <a class="reference external" href="https://
</pre> </pre>
</li> </li>
<li><p class="first">Create a 3x3x3 array with random values</p> <li><p class="first">Create a 3x3x3 array with random values</p>
<blockquote>
<pre class="code python literal-block"> <pre class="code python literal-block">
<span class="name">Z</span> <span class="operator">=</span> <span class="name">np</span><span class="operator">.</span><span class="name">random</span><span class="operator">.</span><span class="name">random</span><span class="punctuation">((</span><span class="literal number integer">3</span><span class="punctuation">,</span><span class="literal number integer">3</span><span class="punctuation">,</span><span class="literal number integer">3</span><span class="punctuation">))</span> <span class="name">Z</span> <span class="operator">=</span> <span class="name">np</span><span class="operator">.</span><span class="name">random</span><span class="operator">.</span><span class="name">random</span><span class="punctuation">((</span><span class="literal number integer">3</span><span class="punctuation">,</span><span class="literal number integer">3</span><span class="punctuation">,</span><span class="literal number integer">3</span><span class="punctuation">))</span>
<span class="keyword">print</span> <span class="name">Z</span> <span class="keyword">print</span> <span class="name">Z</span>
</pre> </pre>
</blockquote>
</li> </li>
</ol>
</div>
<div class="section" id="novice">
<h1>Novice</h1>
<ol class="arabic">
<li><p class="first">Create a 8x8 matrix and fill it with a checkerboard pattern</p> <li><p class="first">Create a 8x8 matrix and fill it with a checkerboard pattern</p>
<pre class="code python literal-block"> <pre class="code python literal-block">
<span class="name">Z</span> <span class="operator">=</span> <span class="name">np</span><span class="operator">.</span><span class="name">zeros</span><span class="punctuation">((</span><span class="literal number integer">8</span><span class="punctuation">,</span><span class="literal number integer">8</span><span class="punctuation">),</span><span class="name">dtype</span><span class="operator">=</span><span class="name builtin">int</span><span class="punctuation">)</span> <span class="name">Z</span> <span class="operator">=</span> <span class="name">np</span><span class="operator">.</span><span class="name">zeros</span><span class="punctuation">((</span><span class="literal number integer">8</span><span class="punctuation">,</span><span class="literal number integer">8</span><span class="punctuation">),</span><span class="name">dtype</span><span class="operator">=</span><span class="name builtin">int</span><span class="punctuation">)</span>
@@ -168,17 +159,14 @@ from the github repo, thanks to the <a class="reference external" href="https://
</pre> </pre>
</li> </li>
<li><p class="first">Create a random vector of size 30 and find the mean value</p> <li><p class="first">Create a random vector of size 30 and find the mean value</p>
<blockquote>
<pre class="code python literal-block"> <pre class="code python literal-block">
<span class="name">Z</span> <span class="operator">=</span> <span class="name">np</span><span class="operator">.</span><span class="name">random</span><span class="operator">.</span><span class="name">random</span><span class="punctuation">(</span><span class="literal number integer">30</span><span class="punctuation">)</span> <span class="name">Z</span> <span class="operator">=</span> <span class="name">np</span><span class="operator">.</span><span class="name">random</span><span class="operator">.</span><span class="name">random</span><span class="punctuation">(</span><span class="literal number integer">30</span><span class="punctuation">)</span>
<span class="name">m</span> <span class="operator">=</span> <span class="name">Z</span><span class="operator">.</span><span class="name">mean</span><span class="punctuation">()</span> <span class="name">m</span> <span class="operator">=</span> <span class="name">Z</span><span class="operator">.</span><span class="name">mean</span><span class="punctuation">()</span>
<span class="keyword">print</span> <span class="name">m</span> <span class="keyword">print</span> <span class="name">m</span>
</pre> </pre>
</blockquote>
</li> </li>
</ol>
</div>
<div class="section" id="apprentice">
<h1>Apprentice</h1>
<ol class="arabic">
<li><p class="first">Make an array immutable (read-only)</p> <li><p class="first">Make an array immutable (read-only)</p>
<pre class="code python literal-block"> <pre class="code python literal-block">
<span class="name">Z</span> <span class="operator">=</span> <span class="name">np</span><span class="operator">.</span><span class="name">zeros</span><span class="punctuation">(</span><span class="literal number integer">10</span><span class="punctuation">)</span> <span class="name">Z</span> <span class="operator">=</span> <span class="name">np</span><span class="operator">.</span><span class="name">zeros</span><span class="punctuation">(</span><span class="literal number integer">10</span><span class="punctuation">)</span>
@@ -267,18 +255,15 @@ point by point distances</p>
</pre> </pre>
</li> </li>
<li><p class="first">Find the nearest value from a given value in an array</p> <li><p class="first">Find the nearest value from a given value in an array</p>
<blockquote>
<pre class="code python literal-block"> <pre class="code python literal-block">
<span class="name">Z</span> <span class="operator">=</span> <span class="name">np</span><span class="operator">.</span><span class="name">random</span><span class="operator">.</span><span class="name">uniform</span><span class="punctuation">(</span><span class="literal number integer">0</span><span class="punctuation">,</span><span class="literal number integer">1</span><span class="punctuation">,</span><span class="literal number integer">10</span><span class="punctuation">)</span> <span class="name">Z</span> <span class="operator">=</span> <span class="name">np</span><span class="operator">.</span><span class="name">random</span><span class="operator">.</span><span class="name">uniform</span><span class="punctuation">(</span><span class="literal number integer">0</span><span class="punctuation">,</span><span class="literal number integer">1</span><span class="punctuation">,</span><span class="literal number integer">10</span><span class="punctuation">)</span>
<span class="name">z</span> <span class="operator">=</span> <span class="literal number float">0.5</span> <span class="name">z</span> <span class="operator">=</span> <span class="literal number float">0.5</span>
<span class="name">m</span> <span class="operator">=</span> <span class="name">Z</span><span class="operator">.</span><span class="name">flat</span><span class="punctuation">[</span><span class="name">np</span><span class="operator">.</span><span class="name">abs</span><span class="punctuation">(</span><span class="name">Z</span> <span class="operator">-</span> <span class="name">z</span><span class="punctuation">)</span><span class="operator">.</span><span class="name">argmin</span><span class="punctuation">()]</span> <span class="name">m</span> <span class="operator">=</span> <span class="name">Z</span><span class="operator">.</span><span class="name">flat</span><span class="punctuation">[</span><span class="name">np</span><span class="operator">.</span><span class="name">abs</span><span class="punctuation">(</span><span class="name">Z</span> <span class="operator">-</span> <span class="name">z</span><span class="punctuation">)</span><span class="operator">.</span><span class="name">argmin</span><span class="punctuation">()]</span>
<span class="keyword">print</span> <span class="name">m</span> <span class="keyword">print</span> <span class="name">m</span>
</pre> </pre>
</blockquote>
</li> </li>
</ol>
</div>
<div class="section" id="journeyman">
<h1>Journeyman</h1>
<ol class="arabic">
<li><p class="first">Consider the following file:</p> <li><p class="first">Consider the following file:</p>
<pre class="literal-block"> <pre class="literal-block">
1,2,3,4,5 1,2,3,4,5
@@ -375,6 +360,7 @@ dimensions (5,5) ?</p>
</pre> </pre>
</li> </li>
<li><p class="first">How to swap two rows of an array ?</p> <li><p class="first">How to swap two rows of an array ?</p>
<blockquote>
<pre class="code python literal-block"> <pre class="code python literal-block">
<span class="comment"># Author: Eelco Hoogendoorn</span> <span class="comment"># Author: Eelco Hoogendoorn</span>
@@ -382,12 +368,8 @@ dimensions (5,5) ?</p>
<span class="name">A</span><span class="punctuation">[[</span><span class="literal number integer">0</span><span class="punctuation">,</span><span class="literal number integer">1</span><span class="punctuation">]]</span> <span class="operator">=</span> <span class="name">A</span><span class="punctuation">[[</span><span class="literal number integer">1</span><span class="punctuation">,</span><span class="literal number integer">0</span><span class="punctuation">]]</span> <span class="name">A</span><span class="punctuation">[[</span><span class="literal number integer">0</span><span class="punctuation">,</span><span class="literal number integer">1</span><span class="punctuation">]]</span> <span class="operator">=</span> <span class="name">A</span><span class="punctuation">[[</span><span class="literal number integer">1</span><span class="punctuation">,</span><span class="literal number integer">0</span><span class="punctuation">]]</span>
<span class="keyword">print</span> <span class="name">A</span> <span class="keyword">print</span> <span class="name">A</span>
</pre> </pre>
</blockquote>
</li> </li>
</ol>
</div>
<div class="section" id="craftsman">
<h1>Craftsman</h1>
<ol class="arabic">
<li><p class="first">Consider a one-dimensional array Z, build a two-dimensional array whose <li><p class="first">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 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])</p> row should be (Z[-3],Z[-2],Z[-1])</p>
@@ -445,9 +427,6 @@ python -c <span class="literal string double">&quot;import numpy; numpy.info(num
</pre> </pre>
</li> </li>
<li><p class="first">How to negate a boolean, or to change the sign of a float inplace ?</p> <li><p class="first">How to negate a boolean, or to change the sign of a float inplace ?</p>
</li>
</ol>
<blockquote>
<pre class="code python literal-block"> <pre class="code python literal-block">
<span class="comment"># Author: Nathaniel J. Smith</span> <span class="comment"># Author: Nathaniel J. Smith</span>
@@ -457,14 +436,7 @@ python -c <span class="literal string double">&quot;import numpy; numpy.info(num
<span class="name">Z</span> <span class="operator">=</span> <span class="name">np</span><span class="operator">.</span><span class="name">random</span><span class="operator">.</span><span class="name">uniform</span><span class="punctuation">(</span><span class="operator">-</span><span class="literal number float">1.0</span><span class="punctuation">,</span><span class="literal number float">1.0</span><span class="punctuation">,</span><span class="literal number integer">100</span><span class="punctuation">)</span> <span class="name">Z</span> <span class="operator">=</span> <span class="name">np</span><span class="operator">.</span><span class="name">random</span><span class="operator">.</span><span class="name">uniform</span><span class="punctuation">(</span><span class="operator">-</span><span class="literal number float">1.0</span><span class="punctuation">,</span><span class="literal number float">1.0</span><span class="punctuation">,</span><span class="literal number integer">100</span><span class="punctuation">)</span>
<span class="name">np</span><span class="operator">.</span><span class="name">negative</span><span class="punctuation">(</span><span class="name">arr</span><span class="punctuation">,</span> <span class="name">out</span><span class="operator">=</span><span class="name">arr</span><span class="punctuation">)</span> <span class="name">np</span><span class="operator">.</span><span class="name">negative</span><span class="punctuation">(</span><span class="name">arr</span><span class="punctuation">,</span> <span class="name">out</span><span class="operator">=</span><span class="name">arr</span><span class="punctuation">)</span>
</pre> </pre>
</blockquote> </li>
<ol class="arabic simple" start="7">
<li></li>
</ol>
</div>
<div class="section" id="artisan">
<h1>Artisan</h1>
<ol class="arabic">
<li><p class="first">Considering a 10x3 matrix, extract rows with unequal values (e.g. [2,2,3])</p> <li><p class="first">Considering a 10x3 matrix, extract rows with unequal values (e.g. [2,2,3])</p>
<pre class="code python literal-block"> <pre class="code python literal-block">
<span class="comment"># Author: Robert Kern</span> <span class="comment"># Author: Robert Kern</span>
@@ -513,11 +485,6 @@ how to compute distance from each point j (P[j]) to each line i (P0[i],P1[i]) ?<
<span class="name">Answer</span> <span class="name">needed</span> <span class="name">actually</span> <span class="name">Answer</span> <span class="name">needed</span> <span class="name">actually</span>
</pre> </pre>
</li> </li>
</ol>
</div>
<div class="section" id="adept">
<h1>Adept</h1>
<ol class="arabic">
<li><p class="first">Consider an arbitrary array, write a function that extract a subpart with a <li><p class="first">Consider an arbitrary array, write a function that extract a subpart with a
fixed shape and centered on a given element (pad with a <tt class="docutils literal">fill</tt> value when fixed shape and centered on a given element (pad with a <tt class="docutils literal">fill</tt> value when
necessary)</p> necessary)</p>
@@ -561,11 +528,6 @@ array R = [[1,2,3,4], [2,3,4,5], [3,4,5,6], ..., [11,12,13,14]] ?</p>
<span class="keyword">print</span> <span class="name">R</span> <span class="keyword">print</span> <span class="name">R</span>
</pre> </pre>
</li> </li>
</ol>
</div>
<div class="section" id="expert">
<h1>Expert</h1>
<ol class="arabic">
<li><p class="first">Consider two arrays A and B of shape (8,3) and (2,2). How to find rows of A <li><p class="first">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 that contain elements of each row of B regardless of the order of the elements
in B ?</p> in B ?</p>
@@ -628,11 +590,6 @@ How to compute the sum of of the p matrix products at once ? (result has shape (
<span class="comment"># and 2 and 1, to remain with a (n,1) vector.</span> <span class="comment"># and 2 and 1, to remain with a (n,1) vector.</span>
</pre> </pre>
</li> </li>
</ol>
</div>
<div class="section" id="master">
<h1>Master</h1>
<ol class="arabic">
<li><p class="first">Given a two dimensional array, how to extract unique rows ?</p> <li><p class="first">Given a two dimensional array, how to extract unique rows ?</p>
<div class="note"> <div class="note">
<p class="first admonition-title">Note</p> <p class="first admonition-title">Note</p>
@@ -671,9 +628,5 @@ How to compute the sum of of the p matrix products at once ? (result has shape (
</li> </li>
</ol> </ol>
</div> </div>
<div class="section" id="archmaster">
<h1>Archmaster</h1>
</div>
</div>
</body> </body>
</html> </html>

View File

@@ -41,22 +41,7 @@
"metadata": {}, "metadata": {},
"source": [ "source": [
"Here is what the page looks like so far:\n", "Here is what the page looks like so far:\n",
"<http://www.loria.fr/~rougier/teaching/numpy.100/index.html>\n" "<http://www.labri.fr/perso/nrougier/teaching/numpy.100/index.html>\n"
]
},
{
"cell_type": "heading",
"level": 1,
"metadata": {},
"source": [
"Note"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The level names came from an old-game (Dungeon Master)\n"
] ]
}, },
{ {
@@ -85,14 +70,6 @@
"version](https://github.com/chezou/julia-100-exercises).\n" "version](https://github.com/chezou/julia-100-exercises).\n"
] ]
}, },
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"Neophyte"
]
},
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {}, "metadata": {},
@@ -205,7 +182,7 @@
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {}, "metadata": {},
"source": [ "source": [
"Find indices of non-zero elements from [1,2,0,0,4,0]\n" "Find indices of non-zero elements from \\[1,2,0,0,4,0\\]\n"
] ]
}, },
{ {
@@ -273,14 +250,6 @@
"metadata": {}, "metadata": {},
"outputs": [] "outputs": []
}, },
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"Novice"
]
},
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {}, "metadata": {},
@@ -473,14 +442,6 @@
"metadata": {}, "metadata": {},
"outputs": [] "outputs": []
}, },
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"Apprentice"
]
},
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {}, "metadata": {},
@@ -547,7 +508,7 @@
"metadata": {}, "metadata": {},
"source": [ "source": [
"Create a structured array with `x` and `y` coordinates covering the\n", "Create a structured array with `x` and `y` coordinates covering the\n",
"[0,1]x[0,1] area.\n" "\\[0,1\\]x\\[0,1\\] area.\n"
] ]
}, },
{ {
@@ -698,14 +659,6 @@
"metadata": {}, "metadata": {},
"outputs": [] "outputs": []
}, },
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"Journeyman"
]
},
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {}, "metadata": {},
@@ -880,7 +833,7 @@
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {}, "metadata": {},
"source": [ "source": [
"Consider the vector [1, 2, 3, 4, 5], how to build a new vector with 3\n", "Consider the vector \\[1, 2, 3, 4, 5\\], how to build a new vector with 3\n",
"consecutive zeros interleaved between each value ?\n" "consecutive zeros interleaved between each value ?\n"
] ]
}, },
@@ -941,21 +894,13 @@
"metadata": {}, "metadata": {},
"outputs": [] "outputs": []
}, },
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"Craftsman"
]
},
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {}, "metadata": {},
"source": [ "source": [
"Consider a one-dimensional array Z, build a two-dimensional array whose\n", "Consider a one-dimensional array Z, build a two-dimensional array whose\n",
"first row is (Z[0],Z[1],Z[2]) and each subsequent row is shifted by 1\n", "first row is (Z\\[0\\],Z\\[1\\],Z\\[2\\]) and each subsequent row is shifted\n",
"(last row should be (Z[-3],Z[-2],Z[-1])\n" "by 1 (last row should be (Z\\[-3\\],Z\\[-2\\],Z\\[-1\\])\n"
] ]
}, },
{ {
@@ -1050,19 +995,49 @@
"outputs": [] "outputs": []
}, },
{ {
"cell_type": "heading", "cell_type": "markdown",
"level": 2,
"metadata": {}, "metadata": {},
"source": [ "source": [
"Artisan" "How to get the documentation of the numpy add function from the command\n",
"line ?\n"
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"python -c \"import numpy; numpy.info(numpy.add)\""
] ]
}, },
{
"cell_type": "markdown",
"metadata": {},
"source": [
"How to negate a boolean, or to change the sign of a float inplace ?\n"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# Author: Nathaniel J. Smith\n",
"\n",
"Z = np.random.randint(0,2,100)\n",
"np.logical_not(arr, out=arr)\n",
"\n",
"Z = np.random.uniform(-1.0,1.0,100)\n",
"np.negative(arr, out=arr)"
],
"language": "python",
"metadata": {},
"outputs": []
},
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {}, "metadata": {},
"source": [ "source": [
"Considering a 10x3 matrix, extract rows with unequal values (e.g.\n", "Considering a 10x3 matrix, extract rows with unequal values (e.g.\n",
"[2,2,3])\n" "\\[2,2,3\\])\n"
] ]
}, },
{ {
@@ -1108,13 +1083,53 @@
"outputs": [] "outputs": []
}, },
{ {
"cell_type": "heading", "cell_type": "markdown",
"level": 2,
"metadata": {}, "metadata": {},
"source": [ "source": [
"Adept" "Consider 2 sets of points P0,P1 describing lines (2d) and a point p, how\n",
"to compute distance from p to each line i (P0\\[i\\],P1\\[i\\]) ?\n"
] ]
}, },
{
"cell_type": "code",
"collapsed": false,
"input": [
"def distance(P0, P1, p):\n",
" T = P1 - P0\n",
" L = (T**2).sum(axis=1)\n",
" U = -((P0[:,0]-p[...,0])*T[:,0] + (P0[:,1]-p[...,1])*T[:,1]) / L\n",
" U = U.reshape(len(U),1)\n",
" D = P0 + U*T - p\n",
" return np.sqrt((D**2).sum(axis=1))\n",
"\n",
"P0 = np.random.uniform(-10,10,(10,2))\n",
"P1 = np.random.uniform(-10,10,(10,2))\n",
"p = np.random.uniform(-10,10,( 1,2))\n",
"print distance(P0, P1, p)"
],
"language": "python",
"metadata": {},
"outputs": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Consider 2 sets of points P0,P1 describing lines (2d) and a set of\n",
"points P, how to compute distance from each point j (P\\[j\\]) to each\n",
"line i (P0\\[i\\],P1\\[i\\]) ?\n"
]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"Answer needed actually"
],
"language": "python",
"metadata": {},
"outputs": []
},
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {}, "metadata": {},
@@ -1161,9 +1176,9 @@
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {}, "metadata": {},
"source": [ "source": [
"Consider an array Z = [1,2,3,4,5,6,7,8,9,10,11,12,13,14], how to\n", "Consider an array Z = \\[1,2,3,4,5,6,7,8,9,10,11,12,13,14\\], how to\n",
"generate an array R = [[1,2,3,4], [2,3,4,5], [3,4,5,6], ...,\n", "generate an array R = \\[\\[1,2,3,4\\], \\[2,3,4,5\\], \\[3,4,5,6\\], ...,\n",
"[11,12,13,14]] ?\n" "\\[11,12,13,14\\]\\] ?\n"
] ]
}, },
{ {
@@ -1180,14 +1195,6 @@
"metadata": {}, "metadata": {},
"outputs": [] "outputs": []
}, },
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"Expert"
]
},
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {}, "metadata": {},
@@ -1242,7 +1249,7 @@
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {}, "metadata": {},
"source": [ "source": [
"Create a 2D array subclass such that Z[i,j] == Z[j,i]\n" "Create a 2D array subclass such that Z\\[i,j\\] == Z\\[j,i\\]\n"
] ]
}, },
{ {
@@ -1299,14 +1306,6 @@
"metadata": {}, "metadata": {},
"outputs": [] "outputs": []
}, },
{
"cell_type": "heading",
"level": 2,
"metadata": {},
"source": [
"Master"
]
},
{ {
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {}, "metadata": {},
@@ -1316,7 +1315,7 @@
}, },
{ {
"cell_type": "heading", "cell_type": "heading",
"level": 2, "level": 1,
"metadata": {}, "metadata": {},
"source": [ "source": [
"Note" "Note"
@@ -1348,12 +1347,37 @@
"outputs": [] "outputs": []
}, },
{ {
"cell_type": "heading", "cell_type": "markdown",
"level": 2,
"metadata": {}, "metadata": {},
"source": [ "source": [
"Archmaster" "How to implement the Game of Life using numpy arrays ?\n"
] ]
},
{
"cell_type": "code",
"collapsed": false,
"input": [
"# Author: Nicolas Rougier\n",
"\n",
"def iterate(Z):\n",
" # Count neighbours\n",
" N = (Z[0:-2,0:-2] + Z[0:-2,1:-1] + Z[0:-2,2:] +\n",
" Z[1:-1,0:-2] + Z[1:-1,2:] +\n",
" Z[2: ,0:-2] + Z[2: ,1:-1] + Z[2: ,2:])\n",
"\n",
" # Apply rules\n",
" birth = (N==3) & (Z[1:-1,1:-1]==0)\n",
" survive = ((N==2) | (N==3)) & (Z[1:-1,1:-1]==1)\n",
" Z[...] = 0\n",
" Z[1:-1,1:-1][birth | survive] = 1\n",
" return Z\n",
"\n",
"Z = np.random.randint(0,2,(50,50))\n",
"for i in range(100): Z = iterate(Z)"
],
"language": "python",
"metadata": {},
"outputs": []
} }
], ],
"metadata": {} "metadata": {}

View File

@@ -24,37 +24,20 @@ is:
Here is what the page looks like so far: Here is what the page looks like so far:
http://www.labri.fr/perso/nrougier/teaching/numpy.100/index.html http://www.labri.fr/perso/nrougier/teaching/numpy.100/index.html
.. Note:: The level names came from an old-game (Dungeon Master)
Repository is at: https://github.com/rougier/numpy-100 Repository is at: https://github.com/rougier/numpy-100
The corresponding `IPython notebook
<https://github.com/rougier/numpy-100/blob/master/README.ipynb>`_ is available
from the github repo, thanks to the `rst2ipynb
<https://github.com/esc/rst2ipynb>`_ conversion tool by `Valentin Haenel
<http://haenel.co>`_
Thanks to Michiaki Ariga, there is now a Thanks to Michiaki Ariga, there is now a
`Julia version <https://github.com/chezou/julia-100-exercises>`_. `Julia version <https://github.com/chezou/julia-100-exercises>`_.
.. **Contents** #. Import the numpy package under the name ``np``
.. .. contents::
.. :local:
.. :depth: 1
Neophyte
========
1. Import the numpy package under the name ``np``
.. code-block:: python .. code-block:: python
import numpy as np import numpy as np
2. Print the numpy version and the configuration. #. Print the numpy version and the configuration.
.. code-block:: python .. code-block:: python
@@ -62,7 +45,7 @@ Neophyte
np.__config__.show() np.__config__.show()
3. Create a null vector of size 10 #. Create a null vector of size 10
.. code-block:: python .. code-block:: python
@@ -70,7 +53,7 @@ Neophyte
print Z print Z
4. Create a null vector of size 10 but the fifth value which is 1 #. Create a null vector of size 10 but the fifth value which is 1
.. code-block:: python .. code-block:: python
@@ -79,7 +62,7 @@ Neophyte
print Z print Z
5. Create a vector with values ranging from 10 to 49 #. Create a vector with values ranging from 10 to 49
.. code-block:: python .. code-block:: python
@@ -87,7 +70,7 @@ Neophyte
print Z print Z
6. Create a 3x3 matrix with values ranging from 0 to 8 #. Create a 3x3 matrix with values ranging from 0 to 8
.. code-block:: python .. code-block:: python
@@ -95,7 +78,7 @@ Neophyte
print Z print Z
7. Find indices of non-zero elements from [1,2,0,0,4,0] #. Find indices of non-zero elements from [1,2,0,0,4,0]
.. code-block:: python .. code-block:: python
@@ -103,7 +86,7 @@ Neophyte
print nz print nz
8. Create a 3x3 identity matrix #. Create a 3x3 identity matrix
.. code-block:: python .. code-block:: python
@@ -111,7 +94,7 @@ Neophyte
print Z print Z
9. Create a 5x5 matrix with values 1,2,3,4 just below the diagonal #. Create a 5x5 matrix with values 1,2,3,4 just below the diagonal
.. code-block:: python .. code-block:: python
@@ -119,18 +102,14 @@ Neophyte
print Z print Z
10. Create a 3x3x3 array with random values #. Create a 3x3x3 array with random values
.. code-block:: python .. code-block:: python
Z = np.random.random((3,3,3)) Z = np.random.random((3,3,3))
print Z print Z
#. Create a 8x8 matrix and fill it with a checkerboard pattern
Novice
======
1. Create a 8x8 matrix and fill it with a checkerboard pattern
.. code-block:: python .. code-block:: python
@@ -140,7 +119,7 @@ Novice
print Z print Z
2. Create a 10x10 array with random values and find the minimum and maximum values #. Create a 10x10 array with random values and find the minimum and maximum values
.. code-block:: python .. code-block:: python
@@ -149,7 +128,7 @@ Novice
print Zmin, Zmax print Zmin, Zmax
3. Create a checkerboard 8x8 matrix using the tile function #. Create a checkerboard 8x8 matrix using the tile function
.. code-block:: python .. code-block:: python
@@ -157,7 +136,7 @@ Novice
print Z print Z
4. Normalize a 5x5 random matrix (between 0 and 1) #. Normalize a 5x5 random matrix (between 0 and 1)
.. code-block:: python .. code-block:: python
@@ -167,7 +146,7 @@ Novice
print Z print Z
5. Multiply a 5x3 matrix by a 3x2 matrix (real matrix product) #. Multiply a 5x3 matrix by a 3x2 matrix (real matrix product)
.. code-block:: python .. code-block:: python
@@ -175,7 +154,7 @@ Novice
print Z print Z
6. Create a 5x5 matrix with row values ranging from 0 to 4 #. Create a 5x5 matrix with row values ranging from 0 to 4
.. code-block:: python .. code-block:: python
@@ -184,7 +163,7 @@ Novice
print Z print Z
7. Create a vector of size 10 with values ranging from 0 to 1, both excluded #. Create a vector of size 10 with values ranging from 0 to 1, both excluded
.. code-block:: python .. code-block:: python
@@ -192,7 +171,7 @@ Novice
print Z print Z
8. Create a random vector of size 10 and sort it #. Create a random vector of size 10 and sort it
.. code-block:: python .. code-block:: python
@@ -201,7 +180,7 @@ Novice
print Z print Z
9. Consider two random array A anb B, check if they are equal. #. Consider two random array A anb B, check if they are equal.
.. code-block:: python .. code-block:: python
@@ -211,7 +190,7 @@ Novice
print equal print equal
10. Create a random vector of size 30 and find the mean value #. Create a random vector of size 30 and find the mean value
.. code-block:: python .. code-block:: python
@@ -220,12 +199,7 @@ Novice
print m print m
#. Make an array immutable (read-only)
Apprentice
==========
1. Make an array immutable (read-only)
.. code-block:: python .. code-block:: python
@@ -234,7 +208,7 @@ Apprentice
Z[0] = 1 Z[0] = 1
2. Consider a random 10x2 matrix representing cartesian coordinates, convert #. Consider a random 10x2 matrix representing cartesian coordinates, convert
them to polar coordinates them to polar coordinates
.. code-block:: python .. code-block:: python
@@ -247,7 +221,7 @@ Apprentice
print T print T
3. Create random vector of size 10 and replace the maximum value by 0 #. Create random vector of size 10 and replace the maximum value by 0
.. code-block:: python .. code-block:: python
@@ -256,7 +230,7 @@ Apprentice
print Z print Z
4. Create a structured array with ``x`` and ``y`` coordinates covering the #. Create a structured array with ``x`` and ``y`` coordinates covering the
[0,1]x[0,1] area. [0,1]x[0,1] area.
.. code-block:: python .. code-block:: python
@@ -267,7 +241,7 @@ Apprentice
print Z print Z
5. Print the minimum and maximum representable value for each numpy scalar type #. Print the minimum and maximum representable value for each numpy scalar type
.. code-block:: python .. code-block:: python
@@ -280,7 +254,7 @@ Apprentice
print np.finfo(dtype).eps print np.finfo(dtype).eps
6. Create a structured array representing a position (x,y) and a color (r,g,b) #. Create a structured array representing a position (x,y) and a color (r,g,b)
.. code-block:: python .. code-block:: python
@@ -292,7 +266,7 @@ Apprentice
print Z print Z
7. Consider a random vector with shape (100,2) representing coordinates, find #. Consider a random vector with shape (100,2) representing coordinates, find
point by point distances point by point distances
.. code-block:: python .. code-block:: python
@@ -309,7 +283,7 @@ Apprentice
print D print D
8. Generate a generic 2D Gaussian-like array #. Generate a generic 2D Gaussian-like array
.. code-block:: python .. code-block:: python
@@ -320,7 +294,7 @@ Apprentice
print G print G
9. How to tell if a given 2D array has null columns ? #. How to tell if a given 2D array has null columns ?
.. code-block:: python .. code-block:: python
@@ -329,7 +303,7 @@ Apprentice
Z = np.random.randint(0,3,(3,10)) Z = np.random.randint(0,3,(3,10))
print (~Z.any(axis=0)).any() print (~Z.any(axis=0)).any()
10. Find the nearest value from a given value in an array #. Find the nearest value from a given value in an array
.. code-block:: python .. code-block:: python
@@ -339,10 +313,7 @@ Apprentice
print m print m
Journeyman #. Consider the following file::
==========
1. Consider the following file::
1,2,3,4,5 1,2,3,4,5
6,,,7,8 6,,,7,8
@@ -355,7 +326,7 @@ Journeyman
Z = np.genfromtxt("missing.dat", delimiter=",") Z = np.genfromtxt("missing.dat", delimiter=",")
2. Consider a generator function that generates 10 integers and use it to build an #. Consider a generator function that generates 10 integers and use it to build an
array array
.. code-block:: python .. code-block:: python
@@ -367,7 +338,7 @@ Journeyman
print Z print Z
3. Consider a given vector, how to add 1 to each element indexed by a second #. Consider a given vector, how to add 1 to each element indexed by a second
vector (be careful with repeated indices) ? vector (be careful with repeated indices) ?
.. code-block:: python .. code-block:: python
@@ -380,7 +351,7 @@ Journeyman
print Z print Z
4. How to accumulate elements of a vector (X) to an array (F) based on an index #. How to accumulate elements of a vector (X) to an array (F) based on an index
list (I) ? list (I) ?
.. code-block:: python .. code-block:: python
@@ -393,7 +364,7 @@ Journeyman
print F print F
5. Considering a (w,h,3) image of (dtype=ubyte), compute the number of unique #. Considering a (w,h,3) image of (dtype=ubyte), compute the number of unique
colors colors
.. code-block:: python .. code-block:: python
@@ -407,7 +378,7 @@ Journeyman
print np.unique(I) print np.unique(I)
6. Considering a four dimensions array, how to get sum over the last two axis at once ? #. Considering a four dimensions array, how to get sum over the last two axis at once ?
.. code-block:: python .. code-block:: python
@@ -416,7 +387,7 @@ Journeyman
print print
7. Considering a one-dimensional vector D, how to compute means of subsets of D #. Considering a one-dimensional vector D, how to compute means of subsets of D
using a vector S of same size describing subset indices ? using a vector S of same size describing subset indices ?
@@ -432,7 +403,7 @@ Journeyman
print D_means print D_means
8. Consider the vector [1, 2, 3, 4, 5], how to build a new vector with 3 #. Consider the vector [1, 2, 3, 4, 5], how to build a new vector with 3
consecutive zeros interleaved between each value ? consecutive zeros interleaved between each value ?
.. code-block:: python .. code-block:: python
@@ -446,7 +417,7 @@ Journeyman
print Z0 print Z0
9. Consider an array of dimension (5,5,3), how to mulitply it by an array with #. Consider an array of dimension (5,5,3), how to mulitply it by an array with
dimensions (5,5) ? dimensions (5,5) ?
.. code-block:: python .. code-block:: python
@@ -456,7 +427,7 @@ Journeyman
print A * B[:,:,None] print A * B[:,:,None]
10. How to swap two rows of an array ? #. How to swap two rows of an array ?
.. code-block:: python .. code-block:: python
@@ -468,10 +439,7 @@ Journeyman
print A print A
Craftsman #. Consider a one-dimensional array Z, build a two-dimensional array whose
=========
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 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]) row should be (Z[-3],Z[-2],Z[-1])
@@ -488,7 +456,7 @@ Craftsman
print Z print Z
2. Consider a set of 10 triplets describing 10 triangles (with shared #. Consider a set of 10 triplets describing 10 triangles (with shared
vertices), find the set of unique line segments composing all the triangles. vertices), find the set of unique line segments composing all the triangles.
.. code-block:: python .. code-block:: python
@@ -504,7 +472,7 @@ Craftsman
print G print G
3. Given an array C that is a bincount, how to produce an array A such that #. Given an array C that is a bincount, how to produce an array A such that
np.bincount(A) == C ? np.bincount(A) == C ?
.. code-block:: python .. code-block:: python
@@ -515,7 +483,7 @@ Craftsman
A = np.repeat(np.arange(len(C)), C) A = np.repeat(np.arange(len(C)), C)
print A print A
4. How to compute averages using a sliding window over an array ? #. How to compute averages using a sliding window over an array ?
.. code-block:: python .. code-block:: python
@@ -528,30 +496,26 @@ Craftsman
Z = np.arange(20) Z = np.arange(20)
print moving_average(Z, n=3) print moving_average(Z, n=3)
5. How to get the documentation of the numpy add function from the command line ? #. How to get the documentation of the numpy add function from the command line ?
.. code-block:: bash .. code-block:: bash
python -c "import numpy; numpy.info(numpy.add)" python -c "import numpy; numpy.info(numpy.add)"
6. How to negate a boolean, or to change the sign of a float inplace ? #. How to negate a boolean, or to change the sign of a float inplace ?
.. code-block:: python .. code-block:: python
# Author: Nathaniel J. Smith # Author: Nathaniel J. Smith
Z = np.random.randint(0,2,100) Z = np.random.randint(0,2,100)
np.logical_not(arr, out=arr) np.logical_not(arr, out=arr)
Z = np.random.uniform(-1.0,1.0,100) Z = np.random.uniform(-1.0,1.0,100)
np.negative(arr, out=arr) np.negative(arr, out=arr)
7.
Artisan #. Considering a 10x3 matrix, extract rows with unequal values (e.g. [2,2,3])
=======
1. Considering a 10x3 matrix, extract rows with unequal values (e.g. [2,2,3])
.. code-block:: python .. code-block:: python
@@ -563,7 +527,7 @@ Artisan
print Z print Z
print U print U
2. Convert a vector of ints into a matrix binary representation. #. Convert a vector of ints into a matrix binary representation.
.. code-block:: python .. code-block:: python
@@ -579,7 +543,7 @@ Artisan
print np.unpackbits(I[:, np.newaxis], axis=1) print np.unpackbits(I[:, np.newaxis], axis=1)
3. Consider 2 sets of points P0,P1 describing lines (2d) and a point p, how to #. Consider 2 sets of points P0,P1 describing lines (2d) and a point p, how to
compute distance from p to each line i (P0[i],P1[i]) ? compute distance from p to each line i (P0[i],P1[i]) ?
.. code-block:: python .. code-block:: python
@@ -598,7 +562,7 @@ Artisan
print distance(P0, P1, p) print distance(P0, P1, p)
4. Consider 2 sets of points P0,P1 describing lines (2d) and a set of points P, #. Consider 2 sets of points P0,P1 describing lines (2d) and a set of points P,
how to compute distance from each point j (P[j]) to each line i (P0[i],P1[i]) ? how to compute distance from each point j (P[j]) to each line i (P0[i],P1[i]) ?
.. code-block:: python .. code-block:: python
@@ -606,11 +570,7 @@ Artisan
Answer needed actually Answer needed actually
#. Consider an arbitrary array, write a function that extract a subpart with a
Adept
=====
1. Consider an arbitrary array, write a function that extract a subpart with a
fixed shape and centered on a given element (pad with a ``fill`` value when fixed shape and centered on a given element (pad with a ``fill`` value when
necessary) necessary)
@@ -645,7 +605,7 @@ Adept
print R print R
2. Consider an array Z = [1,2,3,4,5,6,7,8,9,10,11,12,13,14], how to generate an #. Consider an array Z = [1,2,3,4,5,6,7,8,9,10,11,12,13,14], how to generate an
array R = [[1,2,3,4], [2,3,4,5], [3,4,5,6], ..., [11,12,13,14]] ? array R = [[1,2,3,4], [2,3,4,5], [3,4,5,6], ..., [11,12,13,14]] ?
.. code-block:: python .. code-block:: python
@@ -657,10 +617,7 @@ Adept
print R print R
Expert #. Consider two arrays A and B of shape (8,3) and (2,2). How to find rows of A
======
1. 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 that contain elements of each row of B regardless of the order of the elements
in B ? in B ?
@@ -676,7 +633,7 @@ Expert
print rows print rows
2. Extract all the contiguous 3x3 blocks from a random 10x10 matrix. #. Extract all the contiguous 3x3 blocks from a random 10x10 matrix.
.. code-block:: python .. code-block:: python
@@ -690,7 +647,7 @@ Expert
print C print C
3. Create a 2D array subclass such that Z[i,j] == Z[j,i] #. Create a 2D array subclass such that Z[i,j] == Z[j,i]
.. code-block:: python .. code-block:: python
@@ -709,7 +666,7 @@ Expert
S[2,3] = 42 S[2,3] = 42
print S print S
4. Consider a set of p matrices wich shape (n,n) and a set of p vectors with shape (n,1). #. Consider a set of p matrices wich shape (n,n) and a set of p vectors with shape (n,1).
How to compute the sum of of the p matrix products at once ? (result has shape (n,1)) How to compute the sum of of the p matrix products at once ? (result has shape (n,1))
.. code-block:: python .. code-block:: python
@@ -729,10 +686,7 @@ Expert
# and 2 and 1, to remain with a (n,1) vector. # and 2 and 1, to remain with a (n,1) vector.
Master #. Given a two dimensional array, how to extract unique rows ?
======
1. Given a two dimensional array, how to extract unique rows ?
.. note:: See `stackoverflow <http://stackoverflow.com/questions/16970982/find-unique-rows-in-numpy-array/>`_ for explanations. .. note:: See `stackoverflow <http://stackoverflow.com/questions/16970982/find-unique-rows-in-numpy-array/>`_ for explanations.
@@ -746,7 +700,7 @@ Master
uZ = Z[idx] uZ = Z[idx]
print uZ print uZ
2. How to implement the Game of Life using numpy arrays ? #. How to implement the Game of Life using numpy arrays ?
.. code-block:: python .. code-block:: python
@@ -767,8 +721,3 @@ Master
Z = np.random.randint(0,2,(50,50)) Z = np.random.randint(0,2,(50,50))
for i in range(100): Z = iterate(Z) for i in range(100): Z = iterate(Z)
Archmaster
==========