Compare commits

..

63 Commits

Author SHA1 Message Date
rougier
6cedcb2ad9 solutions update from 7ed0c61 2026-04-29 06:34:30 +00:00
Nicolas P. Rougier
7ed0c61ccd Merge pull request #255 from Nin17/master
correct 2D Gaussian + add separable alternative answer
2026-04-29 08:34:09 +02:00
Chris Ninham
fa2dadf611 correct 2D Gaussian + add separable alternative answer 2026-04-24 14:29:36 +02:00
rougier
e865a958ed solutions update from a4bf63e 2026-02-09 17:44:51 +00:00
Nicolas P. Rougier
a4bf63e6bc Merge pull request #250 from amin-sehati/master
Remove an incorrect solution (fancy indexing) from Numpy exercise No16
2026-02-09 18:44:25 +01:00
Amin Sehati
d421b9750c Added a fancy indexing solution for 16 2026-02-09 08:54:37 -05:00
Amin Sehati
4a3372ed11 Remove an incorrect solution (fancy indexing) from Numpy exercise No. 16 in the solutions files. 2026-02-08 16:58:53 -05:00
rougier
6447594ad6 solutions update from 9642cab 2025-11-06 16:13:10 +00:00
Nicolas P. Rougier
9642cab77c Merge pull request #249 from LegendTejas/fix-issue-247-ktx
Fix #247 : replaced deprecated np.int and corrected formatting in exercises100.ktx
2025-11-06 17:12:45 +01:00
Tejas Tp
4ccd5c0689 Format np.genfromtxt parameters for consistency 2025-11-06 18:49:43 +05:30
Tejas Tp
bfd5e4dbcb Update np.genfromtxt to use int and filling_values
Changed dtype from np.int to int and added filling_values parameter.
2025-11-06 18:45:05 +05:30
Nicolas P. Rougier
564a329151 Re-generated files 2025-08-26 11:15:53 +02:00
rougier
19dcbdd422 solutions update from 5c34811 2025-08-26 09:07:46 +00:00
Nicolas P. Rougier
5c3481111f Merge pull request #244 from Gattocrucco/alt-sol-87
Alternative solution to exercise 87
2025-08-26 11:07:22 +02:00
rougier
2db57d0e16 solutions update from 836eab7 2025-08-26 09:07:01 +00:00
Nicolas P. Rougier
836eab7578 Merge pull request #242 from Gattocrucco/alt-sol-4
Alternative solution to exercise 4
2025-08-26 11:06:42 +02:00
rougier
521b1c0c75 solutions update from 18a5097 2025-08-26 09:06:26 +00:00
Nicolas P. Rougier
18a5097890 Merge pull request #243 from Gattocrucco/improve-sol-82
Improve solution to exercise 82
2025-08-26 11:06:02 +02:00
Gattocrucco
5b6d050a52 reset derived files to original state 2025-08-26 10:56:55 +02:00
Gattocrucco
8ea76d1f91 reset derived files to original state 2025-08-26 10:56:42 +02:00
Gattocrucco
fc72693160 reset derived files to original state 2025-08-26 10:56:10 +02:00
Gattocrucco
301e0eb61e further simplification to the alt solution of 87
The initial formulation contained a redundant `swapaxes`.
2025-08-26 00:16:34 +02:00
Gattocrucco
59a403da66 alternative solution to exercise 87
Added a more elegant (but more cryptic) solution with reshape and
swapaxes.

Removed one of the existing alternative solutions because it was a
duplicate of a previous alternative solution.
2025-08-25 18:13:30 +02:00
Gattocrucco
fca297a6e1 improve solution to exercise 82
The current solution uses a fixed arbitrary threshold of 1e-10 on the
singular values, I replaced it with the common heuristic n*eps*max(s).
2025-08-25 18:06:25 +02:00
Giacomo Petrillo
ed0a067b01 re-generate markdown files 2025-08-25 17:57:43 +02:00
Giacomo Petrillo
ee15dec2c7 alt solution to exercise 4
Uses nbytes instead of itemsize * size
2025-08-25 17:53:21 +02:00
Nicolas P. Rougier
9be9c8cd23 Merge pull request #241 from Hemanth21k/typo_fix
Typo fix for header
2025-07-31 10:27:11 +02:00
Hemanth
7022d36e7a Merge branch 'rougier:master' into typo_fix 2025-07-30 19:00:32 +00:00
Hemanth21k
6bcb01086d fixed typo 2025-07-30 18:58:38 +00:00
rougier
7bd00d196d solutions update from 2bd3a6d 2025-07-28 09:28:51 +00:00
Nicolas P. Rougier
2bd3a6dcf7 Merge pull request #235 from Hemanth21k/q78_edit
Q.78 solution explained with reference
2025-07-28 11:28:29 +02:00
Hemanth
93a34b49b1 Merge branch 'rougier:master' into q78_edit 2025-07-26 23:14:22 +00:00
Hemanth21k
44df2b0d3c simplified answer.78 2025-07-26 23:10:48 +00:00
Hemanth21k
dbb54197e8 q78 explained 2025-07-23 21:52:39 +00:00
rougier
e26c40eff1 solutions update from 1bea088 2025-07-10 09:21:37 +00:00
Nicolas P. Rougier
1bea08864a Merge pull request #236 from Hemanth21k/issue_215_fix
issue 215 fix
2025-07-10 11:21:12 +02:00
Hemanth21k
f7851655d7 issue 215 fix 2025-07-07 17:43:13 +00:00
Hemanth21k
3d136da45b Q.78 solution expalined 2025-07-07 17:28:47 +00:00
Nicolas P. Rougier
2b81a8eb25 Merge pull request #233 from KnightSnape/master
Use default_rng() instead of np.random.random in Exercise #12
2025-05-09 09:35:58 +02:00
KnightSnape
1060e673e0 update Q12 another method 2025-05-09 15:19:16 +08:00
rougier
6b8d5bcc14 solutions update from 00b93cb 2025-04-09 14:23:04 +00:00
Nicolas P. Rougier
00b93cbb23 Merge pull request #231 from Emmet-Ray/Emmet-Ray-fixed-typos
fixed typos
2025-04-09 16:22:39 +02:00
Emmet-Ray
125ae6022f fixed typos
q42: array -> arrays
q48: value -> values
q53: integer -> integer array
q71: mulitply -> multiply
q80: extract -> extracts
q90: combinations -> combination
2025-04-09 16:21:14 +08:00
Nicolas P. Rougier
814f08ea8c Merge pull request #230 from yangwu1227/generator-workflow
feat: generator workflow post-merge
2025-02-19 21:35:29 +01:00
YangWu1227
8077a2ef30 chore: update requirements 2025-02-19 15:20:29 -05:00
YangWu1227
25afa60e10 feat: generator workflow post-merge 2025-02-19 15:18:58 -05:00
Nicolas P. Rougier
af8d83ac89 Update generated files 2025-02-18 08:13:08 +01:00
Nicolas P. Rougier
58ed6a9a86 Merge pull request #229 from yangwu1227/broadcast-solution-exercise-79
broadcasting solution exercise 79
2025-02-18 08:08:17 +01:00
YangWu1227
adf896fa7c feat: broadcasting solution exercise 79 2025-02-17 17:10:33 -05:00
Nicolas P. Rougier
4090dc6c5f Merge pull request #220 from anthonyduong9/solve-exercise-24
solves exercise 24
2025-01-06 13:33:26 +01:00
anthonyduong
efb6e2e192 solves exercise 24 2024-10-22 22:30:16 -07:00
Nicolas P. Rougier
916e1ecf95 Merge pull request #207 from xofbd/specify-python-version
Specify Python version 3.7 to ensure build
2023-12-13 14:23:52 +01:00
Don Fox
0e24ef0013 Specify Python version 3.7 to ensure build 2023-12-03 20:42:32 -05:00
Nicolas P. Rougier
4b759efce8 Regenerate all the files 2023-04-03 09:26:02 +02:00
Nicolas P. Rougier
a4ac12cdc6 Merge pull request #196 from jeremy-feng/master
Fixed a typo
2023-04-03 09:24:11 +02:00
jeremy-feng
683f473a6f Fixed a typo 2023-03-18 15:20:15 +08:00
Nicolas P. Rougier
dc425d7872 Merge pull request #190 from Stefan-Heimersheim/master
Remove incorrect alternative solution q19
2022-12-05 18:41:02 +01:00
Stefan Heimersheim
9182fdc110 Remove incorrect alternative solution q19
The reshape-based solution for q19 did only work for odd numbered squares, not even ones such as 8x8 squares.
2022-11-29 14:29:35 +00:00
Nicolas P. Rougier
e83ba5f309 Fixed generators (see https://github.com/didix21/mdutils/issues/69) 2022-10-17 13:43:14 +02:00
Nicolas P. Rougier
9357b79e1d Merge pull request #189 from HenryJi529/master
Add alternative solution for Q.19
2022-10-17 13:38:53 +02:00
Henry Ji
fccab23c7e Add alternative solution for Q.19 2022-10-10 20:58:25 +08:00
Nicolas P. Rougier
4c45b35878 Merge pull request #177 from RoyiAvital/patch-1
Update README.md
2022-04-10 12:51:45 +02:00
Royi
ed48a838ce Update README.md 2022-04-09 23:37:19 +03:00
13 changed files with 552 additions and 346 deletions

View File

@@ -0,0 +1,46 @@
name: Generate Solutions Files
on:
push:
branches:
- master
paths:
- source/exercises100.ktx
jobs:
generate_files:
runs-on: ubuntu-22.04 # Python 3.7 is not supported on latest Ubuntu
permissions:
contents: write
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Python
uses: actions/setup-python@v5
with:
python-version: '3.7'
cache: 'pip'
- name: Install dependencies
run: pip3 install -r requirements.txt
- name: Generate solutions files
run: python3 generators.py
- name: Set environment variables
run: echo "SHA_SHORT=$(git rev-parse --short $GITHUB_SHA)" >> $GITHUB_ENV
- name: Commit changes
uses: stefanzweifel/git-auto-commit-action@v5
with:
commit_message: "solutions update from ${{ env.SHA_SHORT }}"
file_pattern: >
100_Numpy_exercises.ipynb
100_Numpy_random.ipynb
100_Numpy_exercises.md
100_Numpy_exercises_with_hints.md
100_Numpy_exercises_with_hints_with_solutions.md
100_Numpy_exercises_with_solutions.md

File diff suppressed because it is too large Load Diff

View File

@@ -3,15 +3,12 @@
# 100 numpy exercises
This is a collection of exercises that have been collected in the numpy mailing list, on stack
overflow
This is a collection of exercises that have been collected in the numpy mailing list, on stack overflow
and in the numpy documentation. 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.
and new users but also to provide a set of exercises for those who teach.
If you find an error or think you've a better way to
solve some of them, feel
If you find an error or think you've a better way to solve some of them, feel
free to open an issue at <https://github.com/rougier/numpy-100>.
File automatically generated. See the documentation to update questions/answers/hints programmatically.
@@ -128,7 +125,7 @@ np.sqrt(-1) == np.emath.sqrt(-1)
#### 41. How to sum a small array faster than np.sum? (★★☆)
#### 42. Consider two random array A and B, check if they are equal (★★☆)
#### 42. Consider two random arrays A and B, check if they are equal (★★☆)
#### 43. Make an array immutable (read-only) (★★☆)
@@ -140,7 +137,7 @@ np.sqrt(-1) == np.emath.sqrt(-1)
#### 47. Given two arrays, X and Y, construct the Cauchy matrix C (Cij =1/(xi - yj)) (★★☆)
#### 48. Print the minimum and maximum representable value for each numpy scalar type (★★☆)
#### 48. Print the minimum and maximum representable values for each numpy scalar type (★★☆)
#### 49. How to print all the values of an array? (★★☆)
@@ -150,7 +147,7 @@ np.sqrt(-1) == np.emath.sqrt(-1)
#### 52. Consider a random vector with shape (100,2) representing coordinates, find point by point distances (★★☆)
#### 53. How to convert a float (32 bits) array into an integer (32 bits) in place?
#### 53. How to convert a float (32 bits) array into an integer (32 bits) array in place?
#### 54. How to read the following file? (★★☆)
```
@@ -191,7 +188,7 @@ np.sqrt(-1) == np.emath.sqrt(-1)
#### 70. Consider the vector [1, 2, 3, 4, 5], how to build a new vector with 3 consecutive zeros interleaved between each value? (★★★)
#### 71. Consider an array of dimension (5,5,3), how to mulitply it by an array with dimensions (5,5)? (★★★)
#### 71. Consider an array of dimension (5,5,3), how to multiply it by an array with dimensions (5,5)? (★★★)
#### 72. How to swap two rows of an array? (★★★)
@@ -209,7 +206,7 @@ np.sqrt(-1) == np.emath.sqrt(-1)
#### 79. 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])? (★★★)
#### 80. 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 necessary) (★★★)
#### 80. Consider an arbitrary array, write a function that extracts a subpart with a fixed shape and centered on a given element (pad with a `fill` value when necessary) (★★★)
#### 81. 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]]? (★★★)
@@ -221,7 +218,7 @@ np.sqrt(-1) == np.emath.sqrt(-1)
#### 85. Create a 2D array subclass such that Z[i,j] == Z[j,i] (★★★)
#### 86. 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)) (★★★)
#### 86. Consider a set of p matrices with 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)) (★★★)
#### 87. Consider a 16x16 array, how to get the block-sum (block size is 4x4)? (★★★)
@@ -229,7 +226,7 @@ np.sqrt(-1) == np.emath.sqrt(-1)
#### 89. How to get the n largest values of an array (★★★)
#### 90. Given an arbitrary number of vectors, build the cartesian product (every combinations of every item) (★★★)
#### 90. Given an arbitrary number of vectors, build the cartesian product (every combination of every item) (★★★)
#### 91. How to create a record array from a regular array? (★★★)

View File

@@ -3,15 +3,12 @@
# 100 numpy exercises
This is a collection of exercises that have been collected in the numpy mailing list, on stack
overflow
This is a collection of exercises that have been collected in the numpy mailing list, on stack overflow
and in the numpy documentation. 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.
and new users but also to provide a set of exercises for those who teach.
If you find an error or think you've a better way to
solve some of them, feel
If you find an error or think you've a better way to solve some of them, feel
free to open an issue at <https://github.com/rougier/numpy-100>.
File automatically generated. See the documentation to update questions/answers/hints programmatically.
@@ -128,7 +125,7 @@ np.sqrt(-1) == np.emath.sqrt(-1)
`hint: sort`
#### 41. How to sum a small array faster than np.sum? (★★☆)
`hint: np.add.reduce`
#### 42. Consider two random array A and B, check if they are equal (★★☆)
#### 42. Consider two random arrays A and B, check if they are equal (★★☆)
`hint: np.allclose, np.array_equal`
#### 43. Make an array immutable (read-only) (★★☆)
`hint: flags.writeable`
@@ -140,7 +137,7 @@ np.sqrt(-1) == np.emath.sqrt(-1)
`hint: np.meshgrid`
#### 47. Given two arrays, X and Y, construct the Cauchy matrix C (Cij =1/(xi - yj)) (★★☆)
`hint: np.subtract.outer`
#### 48. Print the minimum and maximum representable value for each numpy scalar type (★★☆)
#### 48. Print the minimum and maximum representable values for each numpy scalar type (★★☆)
`hint: np.iinfo, np.finfo, eps`
#### 49. How to print all the values of an array? (★★☆)
`hint: np.set_printoptions`
@@ -150,7 +147,7 @@ np.sqrt(-1) == np.emath.sqrt(-1)
`hint: dtype`
#### 52. Consider a random vector with shape (100,2) representing coordinates, find point by point distances (★★☆)
`hint: np.atleast_2d, T, np.sqrt`
#### 53. How to convert a float (32 bits) array into an integer (32 bits) in place?
#### 53. How to convert a float (32 bits) array into an integer (32 bits) array in place?
`hint: view and [:] =`
#### 54. How to read the following file? (★★☆)
```
@@ -191,7 +188,7 @@ np.sqrt(-1) == np.emath.sqrt(-1)
`hint: np.diag`
#### 70. Consider the vector [1, 2, 3, 4, 5], how to build a new vector with 3 consecutive zeros interleaved between each value? (★★★)
`hint: array[::4]`
#### 71. Consider an array of dimension (5,5,3), how to mulitply it by an array with dimensions (5,5)? (★★★)
#### 71. Consider an array of dimension (5,5,3), how to multiply it by an array with dimensions (5,5)? (★★★)
`hint: array[:, :, None]`
#### 72. How to swap two rows of an array? (★★★)
`hint: array[[]] = array[[]]`
@@ -209,7 +206,7 @@ np.sqrt(-1) == np.emath.sqrt(-1)
`No hints provided...`
#### 79. 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])? (★★★)
`No hints provided...`
#### 80. 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 necessary) (★★★)
#### 80. Consider an arbitrary array, write a function that extracts a subpart with a fixed shape and centered on a given element (pad with a `fill` value when necessary) (★★★)
`hint: minimum maximum`
#### 81. 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]]? (★★★)
`hint: stride_tricks.as_strided, from numpy.lib.stride_tricks import sliding_window_view (np>=1.20.0)`
@@ -221,7 +218,7 @@ np.sqrt(-1) == np.emath.sqrt(-1)
`hint: stride_tricks.as_strided, from numpy.lib.stride_tricks import sliding_window_view (np>=1.20.0)`
#### 85. Create a 2D array subclass such that Z[i,j] == Z[j,i] (★★★)
`hint: class method`
#### 86. 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)) (★★★)
#### 86. Consider a set of p matrices with 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)) (★★★)
`hint: np.tensordot`
#### 87. Consider a 16x16 array, how to get the block-sum (block size is 4x4)? (★★★)
`hint: np.add.reduceat, from numpy.lib.stride_tricks import sliding_window_view (np>=1.20.0)`
@@ -229,7 +226,7 @@ np.sqrt(-1) == np.emath.sqrt(-1)
`No hints provided...`
#### 89. How to get the n largest values of an array (★★★)
`hint: np.argsort | np.argpartition`
#### 90. Given an arbitrary number of vectors, build the cartesian product (every combinations of every item) (★★★)
#### 90. Given an arbitrary number of vectors, build the cartesian product (every combination of every item) (★★★)
`hint: np.indices`
#### 91. How to create a record array from a regular array? (★★★)
`hint: np.core.records.fromarrays`

View File

@@ -3,15 +3,12 @@
# 100 numpy exercises
This is a collection of exercises that have been collected in the numpy mailing list, on stack
overflow
This is a collection of exercises that have been collected in the numpy mailing list, on stack overflow
and in the numpy documentation. 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.
and new users but also to provide a set of exercises for those who teach.
If you find an error or think you've a better way to
solve some of them, feel
If you find an error or think you've a better way to solve some of them, feel
free to open an issue at <https://github.com/rougier/numpy-100>.
File automatically generated. See the documentation to update questions/answers/hints programmatically.
@@ -41,6 +38,9 @@ print(Z)
```python
Z = np.zeros((10,10))
print("%d bytes" % (Z.size * Z.itemsize))
# Simpler alternative
print("%d bytes" % Z.nbytes)
```
#### 5. How to get the documentation of the numpy add function from the command line? (★☆☆)
`hint: np.info`
@@ -131,7 +131,7 @@ Z = np.ones((5,5))
Z = np.pad(Z, pad_width=1, mode='constant', constant_values=0)
print(Z)
# Using fancy indexing
# Not a solution to this problem but good to know: using fancy indexing for in-place edit
Z[:, [0, -1]] = 0
Z[[0, -1], :] = 0
print(Z)
@@ -205,7 +205,7 @@ color = np.dtype([("r", np.ubyte),
`hint:`
```python
Z = np.dot(np.ones((5,3)), np.ones((3,2)))
Z = np.matmul(np.ones((5, 3)), np.ones((3, 2)))
print(Z)
# Alternative solution, in Python 3.5 and above
@@ -399,7 +399,7 @@ print(Z)
Z = np.arange(10)
np.add.reduce(Z)
```
#### 42. Consider two random array A and B, check if they are equal (★★☆)
#### 42. Consider two random arrays A and B, check if they are equal (★★☆)
`hint: np.allclose, np.array_equal`
```python
@@ -461,7 +461,7 @@ Y = X + 0.5
C = 1.0 / np.subtract.outer(X, Y)
print(np.linalg.det(C))
```
#### 48. Print the minimum and maximum representable value for each numpy scalar type (★★☆)
#### 48. Print the minimum and maximum representable values for each numpy scalar type (★★☆)
`hint: np.iinfo, np.finfo, eps`
```python
@@ -519,7 +519,7 @@ Z = np.random.random((10,2))
D = scipy.spatial.distance.cdist(Z,Z)
print(D)
```
#### 53. How to convert a float (32 bits) array into an integer (32 bits) in place?
#### 53. How to convert a float (32 bits) array into an integer (32 bits) array in place?
`hint: view and [:] =`
```python
@@ -548,7 +548,7 @@ s = StringIO('''1, 2, 3, 4, 5
, , 9,10,11
''')
Z = np.genfromtxt(s, delimiter=",", dtype=np.int)
Z = np.genfromtxt(s, delimiter=",", dtype = int, filling_values = 0)
print(Z)
```
#### 55. What is the equivalent of enumerate for numpy arrays? (★★☆)
@@ -566,9 +566,17 @@ for index in np.ndindex(Z.shape):
```python
X, Y = np.meshgrid(np.linspace(-1, 1, 10), np.linspace(-1, 1, 10))
D = np.sqrt(X*X+Y*Y)
sigma, mu = 1.0, 0.0
G = np.exp(-( (D-mu)**2 / ( 2.0 * sigma**2 ) ) )
G = np.exp(-((X - mu) ** 2 + (Y - mu) ** 2) / (2.0 * sigma**2))
print(G)
# Another solution using the fact that a 2D Gaussian is separable
# Author: Nin17
x = np.linspace(-1, 1, 10)
y = np.linspace(-1, 1, 10)
gx = np.exp(-((x - mu) ** 2 / (2.0 * sigma**2)))
gy = np.exp(-((y - mu) ** 2 / (2.0 * sigma**2)))
G = gy[:, None] * gx[None, :]
print(G)
```
#### 57. How to randomly place p elements in a 2D array? (★★☆)
@@ -615,8 +623,17 @@ print(Z[Z[:,1].argsort()])
```python
# Author: Warren Weckesser
# null : 0
Z = np.random.randint(0,3,(3,10))
print((~Z.any(axis=0)).any())
# null : np.nan
Z=np.array([
[0,1,np.nan],
[1,2,np.nan],
[4,5,np.nan]
])
print(np.isnan(Z).all(axis=0))
```
#### 61. Find the nearest value from a given value in an array (★★☆)
`hint: np.abs, argmin, flat`
@@ -648,7 +665,7 @@ class NamedArray(np.ndarray):
return obj
def __array_finalize__(self, obj):
if obj is None: return
self.info = getattr(obj, 'name', "no name")
self.name = getattr(obj, 'name', "no name")
Z = NamedArray(np.arange(10), "range_10")
print (Z.name)
@@ -766,7 +783,7 @@ Z0 = np.zeros(len(Z) + (len(Z)-1)*(nz))
Z0[::nz+1] = Z
print(Z0)
```
#### 71. Consider an array of dimension (5,5,3), how to mulitply it by an array with dimensions (5,5)? (★★★)
#### 71. Consider an array of dimension (5,5,3), how to multiply it by an array with dimensions (5,5)? (★★★)
`hint: array[:, :, None]`
```python
@@ -864,7 +881,27 @@ np.negative(Z, out=Z)
`No hints provided...`
```python
def distance(P0, P1, p):
P0 = np.random.uniform(-10,10,(10,2))
P1 = np.random.uniform(-10,10,(10,2))
p = np.random.uniform(-10,10,( 1,2))
def distance_faster(P0,P1,p):
#Author: Hemanth Pasupuleti
#Reference: https://mathworld.wolfram.com/Point-LineDistance2-Dimensional.html
v = P1- P0
v[:,[0,1]] = v[:,[1,0]]
v[:,1]*=-1
norm = np.linalg.norm(v,axis=1)
r = P0 - p
d = np.abs(np.einsum("ij,ij->i",r,v)) / norm
return d
print(distance_faster(P0, P1, p))
##--------------- OR ---------------##
def distance_slower(P0, P1, p):
T = P1 - P0
L = (T**2).sum(axis=1)
U = -((P0[:,0]-p[...,0])*T[:,0] + (P0[:,1]-p[...,1])*T[:,1]) / L
@@ -872,10 +909,7 @@ def distance(P0, P1, p):
D = P0 + U*T - p
return np.sqrt((D**2).sum(axis=1))
P0 = np.random.uniform(-10,10,(10,2))
P1 = np.random.uniform(-10,10,(10,2))
p = np.random.uniform(-10,10,( 1,2))
print(distance(P0, P1, p))
print(distance_slower(P0, P1, p))
```
#### 79. 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])? (★★★)
`No hints provided...`
@@ -888,8 +922,34 @@ P0 = np.random.uniform(-10, 10, (10,2))
P1 = np.random.uniform(-10,10,(10,2))
p = np.random.uniform(-10, 10, (10,2))
print(np.array([distance(P0,P1,p_i) for p_i in p]))
# Author: Yang Wu (Broadcasting)
def distance_points_to_lines(p: np.ndarray, p_1: np.ndarray, p_2: np.ndarray) -> np.ndarray:
x_0, y_0 = p.T # Shape -> (n points, )
x_1, y_1 = p_1.T # Shape -> (n lines, )
x_2, y_2 = p_2.T # Shape -> (n lines, )
# Displacement vector coordinates from p_1 -> p_2
dx = x_2 - x_1 # Shape -> (n lines, )
dy = y_2 - y_1 # Shape -> (n lines, )
# The 'cross product' term
cross_term = x_2 * y_1 - y_2 * x_1 # Shape -> (n lines, )
# Broadcast x_0, y_0 (n points, 1) and dx, dy, cross_term (1, n lines) -> (n points, n lines)
numerator = np.abs(
dy[np.newaxis, :] * x_0[:, np.newaxis]
- dx[np.newaxis, :] * y_0[:, np.newaxis]
+ cross_term[np.newaxis, :]
)
denominator = np.sqrt(dx**2 + dy**2) # Shape -> (n lines, )
# Shape (n points, n lines) / (1, n_lines) -> (n points, n lines)
return numerator / denominator[np.newaxis, :]
distance_points_to_lines(p, P0, P1)
```
#### 80. 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 necessary) (★★★)
#### 80. Consider an arbitrary array, write a function that extracts a subpart with a fixed shape and centered on a given element (pad with a `fill` value when necessary) (★★★)
`hint: minimum maximum`
```python
@@ -915,8 +975,8 @@ Z_start = (np.maximum(Z_start,0)).tolist()
R_stop = np.maximum(R_start, (R_stop - np.maximum(Z_stop-Zs,0))).tolist()
Z_stop = (np.minimum(Z_stop,Zs)).tolist()
r = [slice(start,stop) for start,stop in zip(R_start,R_stop)]
z = [slice(start,stop) for start,stop in zip(Z_start,Z_stop)]
r = tuple([slice(start,stop) for start,stop in zip(R_start,R_stop)])
z = tuple([slice(start,stop) for start,stop in zip(Z_start,Z_stop)])
R[r] = Z[z]
print(Z)
print(R)
@@ -944,7 +1004,8 @@ print(sliding_window_view(Z, window_shape=4))
Z = np.random.uniform(0,1,(10,10))
U, S, V = np.linalg.svd(Z) # Singular Value Decomposition
rank = np.sum(S > 1e-10)
threshold = len(S) * S.max() * np.finfo(S.dtype).eps
rank = np.sum(S > threshold)
print(rank)
# alternative solution:
@@ -998,7 +1059,7 @@ S = symetric(np.random.randint(0,10,(5,5)))
S[2,3] = 42
print(S)
```
#### 86. 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)) (★★★)
#### 86. Consider a set of p matrices with 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)) (★★★)
`hint: np.tensordot`
```python
@@ -1037,11 +1098,8 @@ k = 4
windows = np.lib.stride_tricks.sliding_window_view(Z, (k, k))
S = windows[::k, ::k, ...].sum(axis=(-2, -1))
# Author: Jeff Luo (@Jeff1999)
Z = np.ones((16, 16))
k = 4
print(sliding_window_view(Z, window_shape=(k, k))[::k, ::k].sum(axis=(-2, -1)))
# alternative solution (by @Gattocrucco)
S = Z.reshape(4, 4, 4, 4).sum((1, 3))
```
#### 88. How to implement the Game of Life using numpy arrays? (★★★)
`No hints provided...`
@@ -1080,7 +1138,7 @@ print (Z[np.argsort(Z)[-n:]])
# Fast
print (Z[np.argpartition(-Z,n)[:n]])
```
#### 90. Given an arbitrary number of vectors, build the cartesian product (every combinations of every item) (★★★)
#### 90. Given an arbitrary number of vectors, build the cartesian product (every combination of every item) (★★★)
`hint: np.indices`
```python

View File

@@ -3,15 +3,12 @@
# 100 numpy exercises
This is a collection of exercises that have been collected in the numpy mailing list, on stack
overflow
This is a collection of exercises that have been collected in the numpy mailing list, on stack overflow
and in the numpy documentation. 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.
and new users but also to provide a set of exercises for those who teach.
If you find an error or think you've a better way to
solve some of them, feel
If you find an error or think you've a better way to solve some of them, feel
free to open an issue at <https://github.com/rougier/numpy-100>.
File automatically generated. See the documentation to update questions/answers/hints programmatically.
@@ -41,6 +38,9 @@ print(Z)
```python
Z = np.zeros((10,10))
print("%d bytes" % (Z.size * Z.itemsize))
# Simpler alternative
print("%d bytes" % Z.nbytes)
```
#### 5. How to get the documentation of the numpy add function from the command line? (★☆☆)
@@ -131,7 +131,7 @@ Z = np.ones((5,5))
Z = np.pad(Z, pad_width=1, mode='constant', constant_values=0)
print(Z)
# Using fancy indexing
# Not a solution to this problem but good to know: using fancy indexing for in-place edit
Z[:, [0, -1]] = 0
Z[[0, -1], :] = 0
print(Z)
@@ -205,7 +205,7 @@ color = np.dtype([("r", np.ubyte),
```python
Z = np.dot(np.ones((5,3)), np.ones((3,2)))
Z = np.matmul(np.ones((5, 3)), np.ones((3, 2)))
print(Z)
# Alternative solution, in Python 3.5 and above
@@ -399,7 +399,7 @@ print(Z)
Z = np.arange(10)
np.add.reduce(Z)
```
#### 42. Consider two random array A and B, check if they are equal (★★☆)
#### 42. Consider two random arrays A and B, check if they are equal (★★☆)
```python
@@ -461,7 +461,7 @@ Y = X + 0.5
C = 1.0 / np.subtract.outer(X, Y)
print(np.linalg.det(C))
```
#### 48. Print the minimum and maximum representable value for each numpy scalar type (★★☆)
#### 48. Print the minimum and maximum representable values for each numpy scalar type (★★☆)
```python
@@ -519,7 +519,7 @@ Z = np.random.random((10,2))
D = scipy.spatial.distance.cdist(Z,Z)
print(D)
```
#### 53. How to convert a float (32 bits) array into an integer (32 bits) in place?
#### 53. How to convert a float (32 bits) array into an integer (32 bits) array in place?
```python
@@ -548,7 +548,7 @@ s = StringIO('''1, 2, 3, 4, 5
, , 9,10,11
''')
Z = np.genfromtxt(s, delimiter=",", dtype=np.int)
Z = np.genfromtxt(s, delimiter=",", dtype = int, filling_values = 0)
print(Z)
```
#### 55. What is the equivalent of enumerate for numpy arrays? (★★☆)
@@ -566,9 +566,17 @@ for index in np.ndindex(Z.shape):
```python
X, Y = np.meshgrid(np.linspace(-1, 1, 10), np.linspace(-1, 1, 10))
D = np.sqrt(X*X+Y*Y)
sigma, mu = 1.0, 0.0
G = np.exp(-( (D-mu)**2 / ( 2.0 * sigma**2 ) ) )
G = np.exp(-((X - mu) ** 2 + (Y - mu) ** 2) / (2.0 * sigma**2))
print(G)
# Another solution using the fact that a 2D Gaussian is separable
# Author: Nin17
x = np.linspace(-1, 1, 10)
y = np.linspace(-1, 1, 10)
gx = np.exp(-((x - mu) ** 2 / (2.0 * sigma**2)))
gy = np.exp(-((y - mu) ** 2 / (2.0 * sigma**2)))
G = gy[:, None] * gx[None, :]
print(G)
```
#### 57. How to randomly place p elements in a 2D array? (★★☆)
@@ -615,8 +623,17 @@ print(Z[Z[:,1].argsort()])
```python
# Author: Warren Weckesser
# null : 0
Z = np.random.randint(0,3,(3,10))
print((~Z.any(axis=0)).any())
# null : np.nan
Z=np.array([
[0,1,np.nan],
[1,2,np.nan],
[4,5,np.nan]
])
print(np.isnan(Z).all(axis=0))
```
#### 61. Find the nearest value from a given value in an array (★★☆)
@@ -648,7 +665,7 @@ class NamedArray(np.ndarray):
return obj
def __array_finalize__(self, obj):
if obj is None: return
self.info = getattr(obj, 'name', "no name")
self.name = getattr(obj, 'name', "no name")
Z = NamedArray(np.arange(10), "range_10")
print (Z.name)
@@ -766,7 +783,7 @@ Z0 = np.zeros(len(Z) + (len(Z)-1)*(nz))
Z0[::nz+1] = Z
print(Z0)
```
#### 71. Consider an array of dimension (5,5,3), how to mulitply it by an array with dimensions (5,5)? (★★★)
#### 71. Consider an array of dimension (5,5,3), how to multiply it by an array with dimensions (5,5)? (★★★)
```python
@@ -864,7 +881,27 @@ np.negative(Z, out=Z)
```python
def distance(P0, P1, p):
P0 = np.random.uniform(-10,10,(10,2))
P1 = np.random.uniform(-10,10,(10,2))
p = np.random.uniform(-10,10,( 1,2))
def distance_faster(P0,P1,p):
#Author: Hemanth Pasupuleti
#Reference: https://mathworld.wolfram.com/Point-LineDistance2-Dimensional.html
v = P1- P0
v[:,[0,1]] = v[:,[1,0]]
v[:,1]*=-1
norm = np.linalg.norm(v,axis=1)
r = P0 - p
d = np.abs(np.einsum("ij,ij->i",r,v)) / norm
return d
print(distance_faster(P0, P1, p))
##--------------- OR ---------------##
def distance_slower(P0, P1, p):
T = P1 - P0
L = (T**2).sum(axis=1)
U = -((P0[:,0]-p[...,0])*T[:,0] + (P0[:,1]-p[...,1])*T[:,1]) / L
@@ -872,10 +909,7 @@ def distance(P0, P1, p):
D = P0 + U*T - p
return np.sqrt((D**2).sum(axis=1))
P0 = np.random.uniform(-10,10,(10,2))
P1 = np.random.uniform(-10,10,(10,2))
p = np.random.uniform(-10,10,( 1,2))
print(distance(P0, P1, p))
print(distance_slower(P0, P1, p))
```
#### 79. 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])? (★★★)
@@ -888,8 +922,34 @@ P0 = np.random.uniform(-10, 10, (10,2))
P1 = np.random.uniform(-10,10,(10,2))
p = np.random.uniform(-10, 10, (10,2))
print(np.array([distance(P0,P1,p_i) for p_i in p]))
# Author: Yang Wu (Broadcasting)
def distance_points_to_lines(p: np.ndarray, p_1: np.ndarray, p_2: np.ndarray) -> np.ndarray:
x_0, y_0 = p.T # Shape -> (n points, )
x_1, y_1 = p_1.T # Shape -> (n lines, )
x_2, y_2 = p_2.T # Shape -> (n lines, )
# Displacement vector coordinates from p_1 -> p_2
dx = x_2 - x_1 # Shape -> (n lines, )
dy = y_2 - y_1 # Shape -> (n lines, )
# The 'cross product' term
cross_term = x_2 * y_1 - y_2 * x_1 # Shape -> (n lines, )
# Broadcast x_0, y_0 (n points, 1) and dx, dy, cross_term (1, n lines) -> (n points, n lines)
numerator = np.abs(
dy[np.newaxis, :] * x_0[:, np.newaxis]
- dx[np.newaxis, :] * y_0[:, np.newaxis]
+ cross_term[np.newaxis, :]
)
denominator = np.sqrt(dx**2 + dy**2) # Shape -> (n lines, )
# Shape (n points, n lines) / (1, n_lines) -> (n points, n lines)
return numerator / denominator[np.newaxis, :]
distance_points_to_lines(p, P0, P1)
```
#### 80. 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 necessary) (★★★)
#### 80. Consider an arbitrary array, write a function that extracts a subpart with a fixed shape and centered on a given element (pad with a `fill` value when necessary) (★★★)
```python
@@ -915,8 +975,8 @@ Z_start = (np.maximum(Z_start,0)).tolist()
R_stop = np.maximum(R_start, (R_stop - np.maximum(Z_stop-Zs,0))).tolist()
Z_stop = (np.minimum(Z_stop,Zs)).tolist()
r = [slice(start,stop) for start,stop in zip(R_start,R_stop)]
z = [slice(start,stop) for start,stop in zip(Z_start,Z_stop)]
r = tuple([slice(start,stop) for start,stop in zip(R_start,R_stop)])
z = tuple([slice(start,stop) for start,stop in zip(Z_start,Z_stop)])
R[r] = Z[z]
print(Z)
print(R)
@@ -944,7 +1004,8 @@ print(sliding_window_view(Z, window_shape=4))
Z = np.random.uniform(0,1,(10,10))
U, S, V = np.linalg.svd(Z) # Singular Value Decomposition
rank = np.sum(S > 1e-10)
threshold = len(S) * S.max() * np.finfo(S.dtype).eps
rank = np.sum(S > threshold)
print(rank)
# alternative solution:
@@ -998,7 +1059,7 @@ S = symetric(np.random.randint(0,10,(5,5)))
S[2,3] = 42
print(S)
```
#### 86. 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)) (★★★)
#### 86. Consider a set of p matrices with 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)) (★★★)
```python
@@ -1037,11 +1098,8 @@ k = 4
windows = np.lib.stride_tricks.sliding_window_view(Z, (k, k))
S = windows[::k, ::k, ...].sum(axis=(-2, -1))
# Author: Jeff Luo (@Jeff1999)
Z = np.ones((16, 16))
k = 4
print(sliding_window_view(Z, window_shape=(k, k))[::k, ::k].sum(axis=(-2, -1)))
# alternative solution (by @Gattocrucco)
S = Z.reshape(4, 4, 4, 4).sum((1, 3))
```
#### 88. How to implement the Game of Life using numpy arrays? (★★★)
@@ -1080,7 +1138,7 @@ print (Z[np.argsort(Z)[-n:]])
# Fast
print (Z[np.argpartition(-Z,n)[:n]])
```
#### 90. Given an arbitrary number of vectors, build the cartesian product (every combinations of every item) (★★★)
#### 90. Given an arbitrary number of vectors, build the cartesian product (every combination of every item) (★★★)
```python

View File

@@ -2,7 +2,7 @@
"cells": [
{
"cell_type": "markdown",
"id": "a194d42e",
"id": "94b10be0",
"metadata": {},
"source": [
"# 100 numpy exercises\n",
@@ -18,7 +18,7 @@
},
{
"cell_type": "markdown",
"id": "a7fd49f7",
"id": "1d0b9900",
"metadata": {},
"source": [
"File automatically generated. See the documentation to update questions/answers/hints programmatically."
@@ -26,17 +26,17 @@
},
{
"cell_type": "markdown",
"id": "b702d5a2",
"id": "21313ae9",
"metadata": {},
"source": [
"Run the `initialize.py` module, then call a random question with `pick()` an hint towards its solution with\n",
"Run the `initialise.py` module, then call a random question with `pick()` an hint towards its solution with\n",
"`hint(n)` and the answer with `answer(n)`, where n is the number of the picked question."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "da60e1d0",
"id": "c4ad3a14",
"metadata": {},
"outputs": [],
"source": [
@@ -46,7 +46,7 @@
{
"cell_type": "code",
"execution_count": null,
"id": "9fb544fe",
"id": "13bdf6d0",
"metadata": {},
"outputs": [],
"source": [

View File

@@ -19,5 +19,4 @@ This work is licensed under the MIT license.
### Variants in Other Languages
#### Julia
- [100 Julia Exercises](https://github.com/RoyiAvital/Julia100Exercises).
- **Julia**: [100 Julia Exercises](https://github.com/RoyiAvital/Julia100Exercises).

View File

@@ -108,7 +108,7 @@ def create_markdown(destination_filename='100_Numpy_exercises', with_hints=False
# Add questions (and hint or answers if required)
for n in range(1, 101):
mdfile.new_header(title=f"{n}. {QHA[f'q{n}']}", level=4)
mdfile.new_header(title=f"{n}. {QHA[f'q{n}']}", level=4, add_table_of_contents="n")
if with_hints:
mdfile.write(f"`{QHA[f'h{n}']}`")
if with_solutions:

View File

@@ -1,5 +1,3 @@
numpy==1.17.4
pandas==0.25.3
jupyter==1.0.0
jupyterthemes==0.20.0
mdutils==1.0.0
numpy
mdutils
nbformat

1
runtime.txt Normal file
View File

@@ -0,0 +1 @@
python-3.7.17

View File

@@ -37,6 +37,9 @@ hint: size, itemsize
Z = np.zeros((10,10))
print("%d bytes" % (Z.size * Z.itemsize))
# Simpler alternative
print("%d bytes" % Z.nbytes)
< q5
How to get the documentation of the numpy add function from the command line? (★☆☆)
@@ -162,7 +165,7 @@ Z = np.ones((5,5))
Z = np.pad(Z, pad_width=1, mode='constant', constant_values=0)
print(Z)
# Using fancy indexing
# Not a solution to this problem but good to know: using fancy indexing for in-place edit
Z[:, [0, -1]] = 0
Z[[0, -1], :] = 0
print(Z)
@@ -260,7 +263,7 @@ Multiply a 5x3 matrix by a 3x2 matrix (real matrix product) (★☆☆)
hint:
< a24
Z = np.dot(np.ones((5,3)), np.ones((3,2)))
Z = np.matmul(np.ones((5, 3)), np.ones((3, 2)))
print(Z)
# Alternative solution, in Python 3.5 and above
@@ -506,7 +509,7 @@ Z = np.arange(10)
np.add.reduce(Z)
< q42
Consider two random array A and B, check if they are equal (★★☆)
Consider two random arrays A and B, check if they are equal (★★☆)
< h42
hint: np.allclose, np.array_equal
@@ -586,7 +589,7 @@ C = 1.0 / np.subtract.outer(X, Y)
print(np.linalg.det(C))
< q48
Print the minimum and maximum representable value for each numpy scalar type (★★☆)
Print the minimum and maximum representable values for each numpy scalar type (★★☆)
< h48
hint: np.iinfo, np.finfo, eps
@@ -659,7 +662,7 @@ D = scipy.spatial.distance.cdist(Z,Z)
print(D)
< q53
How to convert a float (32 bits) array into an integer (32 bits) in place?
How to convert a float (32 bits) array into an integer (32 bits) array in place?
< h53
hint: view and [:] =
@@ -693,7 +696,7 @@ s = StringIO('''1, 2, 3, 4, 5
, , 9,10,11
''')
Z = np.genfromtxt(s, delimiter=",", dtype=np.int)
Z = np.genfromtxt(s, delimiter=",", dtype = int, filling_values = 0)
print(Z)
< q55
@@ -717,9 +720,17 @@ hint: np.meshgrid, np.exp
< a56
X, Y = np.meshgrid(np.linspace(-1, 1, 10), np.linspace(-1, 1, 10))
D = np.sqrt(X*X+Y*Y)
sigma, mu = 1.0, 0.0
G = np.exp(-( (D-mu)**2 / ( 2.0 * sigma**2 ) ) )
G = np.exp(-((X - mu) ** 2 + (Y - mu) ** 2) / (2.0 * sigma**2))
print(G)
# Another solution using the fact that a 2D Gaussian is separable
# Author: Nin17
x = np.linspace(-1, 1, 10)
y = np.linspace(-1, 1, 10)
gx = np.exp(-((x - mu) ** 2 / (2.0 * sigma**2)))
gy = np.exp(-((y - mu) ** 2 / (2.0 * sigma**2)))
G = gy[:, None] * gx[None, :]
print(G)
< q57
@@ -969,7 +980,7 @@ Z0[::nz+1] = Z
print(Z0)
< q71
Consider an array of dimension (5,5,3), how to mulitply it by an array with dimensions (5,5)? (★★★)
Consider an array of dimension (5,5,3), how to multiply it by an array with dimensions (5,5)? (★★★)
< h71
hint: array[:, :, None]
@@ -1090,7 +1101,27 @@ Consider 2 sets of points P0,P1 describing lines (2d) and a point p, how to comp
No hints provided...
< a78
def distance(P0, P1, p):
P0 = np.random.uniform(-10,10,(10,2))
P1 = np.random.uniform(-10,10,(10,2))
p = np.random.uniform(-10,10,( 1,2))
def distance_faster(P0,P1,p):
#Author: Hemanth Pasupuleti
#Reference: https://mathworld.wolfram.com/Point-LineDistance2-Dimensional.html
v = P1- P0
v[:,[0,1]] = v[:,[1,0]]
v[:,1]*=-1
norm = np.linalg.norm(v,axis=1)
r = P0 - p
d = np.abs(np.einsum("ij,ij->i",r,v)) / norm
return d
print(distance_faster(P0, P1, p))
##--------------- OR ---------------##
def distance_slower(P0, P1, p):
T = P1 - P0
L = (T**2).sum(axis=1)
U = -((P0[:,0]-p[...,0])*T[:,0] + (P0[:,1]-p[...,1])*T[:,1]) / L
@@ -1098,10 +1129,7 @@ def distance(P0, P1, p):
D = P0 + U*T - p
return np.sqrt((D**2).sum(axis=1))
P0 = np.random.uniform(-10,10,(10,2))
P1 = np.random.uniform(-10,10,(10,2))
p = np.random.uniform(-10,10,( 1,2))
print(distance(P0, P1, p))
print(distance_slower(P0, P1, p))
< q79
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])? (★★★)
@@ -1118,8 +1146,34 @@ P1 = np.random.uniform(-10,10,(10,2))
p = np.random.uniform(-10, 10, (10,2))
print(np.array([distance(P0,P1,p_i) for p_i in p]))
# Author: Yang Wu (Broadcasting)
def distance_points_to_lines(p: np.ndarray, p_1: np.ndarray, p_2: np.ndarray) -> np.ndarray:
x_0, y_0 = p.T # Shape -> (n points, )
x_1, y_1 = p_1.T # Shape -> (n lines, )
x_2, y_2 = p_2.T # Shape -> (n lines, )
# Displacement vector coordinates from p_1 -> p_2
dx = x_2 - x_1 # Shape -> (n lines, )
dy = y_2 - y_1 # Shape -> (n lines, )
# The 'cross product' term
cross_term = x_2 * y_1 - y_2 * x_1 # Shape -> (n lines, )
# Broadcast x_0, y_0 (n points, 1) and dx, dy, cross_term (1, n lines) -> (n points, n lines)
numerator = np.abs(
dy[np.newaxis, :] * x_0[:, np.newaxis]
- dx[np.newaxis, :] * y_0[:, np.newaxis]
+ cross_term[np.newaxis, :]
)
denominator = np.sqrt(dx**2 + dy**2) # Shape -> (n lines, )
# Shape (n points, n lines) / (1, n_lines) -> (n points, n lines)
return numerator / denominator[np.newaxis, :]
distance_points_to_lines(p, P0, P1)
< q80
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 necessary) (★★★)
Consider an arbitrary array, write a function that extracts a subpart with a fixed shape and centered on a given element (pad with a `fill` value when necessary) (★★★)
< h80
hint: minimum maximum
@@ -1147,8 +1201,8 @@ Z_start = (np.maximum(Z_start,0)).tolist()
R_stop = np.maximum(R_start, (R_stop - np.maximum(Z_stop-Zs,0))).tolist()
Z_stop = (np.minimum(Z_stop,Zs)).tolist()
r = [slice(start,stop) for start,stop in zip(R_start,R_stop)]
z = [slice(start,stop) for start,stop in zip(Z_start,Z_stop)]
r = tuple([slice(start,stop) for start,stop in zip(R_start,R_stop)])
z = tuple([slice(start,stop) for start,stop in zip(Z_start,Z_stop)])
R[r] = Z[z]
print(Z)
print(R)
@@ -1182,7 +1236,8 @@ hint: np.linalg.svd, np.linalg.matrix_rank
Z = np.random.uniform(0,1,(10,10))
U, S, V = np.linalg.svd(Z) # Singular Value Decomposition
rank = np.sum(S > 1e-10)
threshold = len(S) * S.max() * np.finfo(S.dtype).eps
rank = np.sum(S > threshold)
print(rank)
# alternative solution:
@@ -1246,7 +1301,7 @@ S[2,3] = 42
print(S)
< q86
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)) (★★★)
Consider a set of p matrices with 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)) (★★★)
< h86
hint: np.tensordot
@@ -1290,11 +1345,8 @@ k = 4
windows = np.lib.stride_tricks.sliding_window_view(Z, (k, k))
S = windows[::k, ::k, ...].sum(axis=(-2, -1))
# Author: Jeff Luo (@Jeff1999)
Z = np.ones((16, 16))
k = 4
print(sliding_window_view(Z, window_shape=(k, k))[::k, ::k].sum(axis=(-2, -1)))
# alternative solution (by @Gattocrucco)
S = Z.reshape(4, 4, 4, 4).sum((1, 3))
< q88
How to implement the Game of Life using numpy arrays? (★★★)
@@ -1340,7 +1392,7 @@ print (Z[np.argsort(Z)[-n:]])
print (Z[np.argpartition(-Z,n)[:n]])
< q90
Given an arbitrary number of vectors, build the cartesian product (every combinations of every item) (★★★)
Given an arbitrary number of vectors, build the cartesian product (every combination of every item) (★★★)
< h90
hint: np.indices

View File

@@ -15,11 +15,11 @@ File automatically generated. See the documentation to update questions/answers/
< jupyter_instruction
Run the `initialize.py` module, then for each question you can query the
Run the `initialise.py` module, then for each question you can query the
answer or an hint with `hint(n)` or `answer(n)` for `n` question number.
< jupyter_instruction_rand
Run the `initialize.py` module, then call a random question with `pick()` an hint towards its solution with
Run the `initialise.py` module, then call a random question with `pick()` an hint towards its solution with
`hint(n)` and the answer with `answer(n)`, where n is the number of the picked question.