Compare commits
63 Commits
8366787686
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6cedcb2ad9 | ||
|
|
7ed0c61ccd | ||
|
|
fa2dadf611 | ||
|
|
e865a958ed | ||
|
|
a4bf63e6bc | ||
|
|
d421b9750c | ||
|
|
4a3372ed11 | ||
|
|
6447594ad6 | ||
|
|
9642cab77c | ||
|
|
4ccd5c0689 | ||
|
|
bfd5e4dbcb | ||
|
|
564a329151 | ||
|
|
19dcbdd422 | ||
|
|
5c3481111f | ||
|
|
2db57d0e16 | ||
|
|
836eab7578 | ||
|
|
521b1c0c75 | ||
|
|
18a5097890 | ||
|
|
5b6d050a52 | ||
|
|
8ea76d1f91 | ||
|
|
fc72693160 | ||
|
|
301e0eb61e | ||
|
|
59a403da66 | ||
|
|
fca297a6e1 | ||
|
|
ed0a067b01 | ||
|
|
ee15dec2c7 | ||
|
|
9be9c8cd23 | ||
|
|
7022d36e7a | ||
|
|
6bcb01086d | ||
|
|
7bd00d196d | ||
|
|
2bd3a6dcf7 | ||
|
|
93a34b49b1 | ||
|
|
44df2b0d3c | ||
|
|
dbb54197e8 | ||
|
|
e26c40eff1 | ||
|
|
1bea08864a | ||
|
|
f7851655d7 | ||
|
|
3d136da45b | ||
|
|
2b81a8eb25 | ||
|
|
1060e673e0 | ||
|
|
6b8d5bcc14 | ||
|
|
00b93cbb23 | ||
|
|
125ae6022f | ||
|
|
814f08ea8c | ||
|
|
8077a2ef30 | ||
|
|
25afa60e10 | ||
|
|
af8d83ac89 | ||
|
|
58ed6a9a86 | ||
|
|
adf896fa7c | ||
|
|
4090dc6c5f | ||
|
|
efb6e2e192 | ||
|
|
916e1ecf95 | ||
|
|
0e24ef0013 | ||
|
|
4b759efce8 | ||
|
|
a4ac12cdc6 | ||
|
|
683f473a6f | ||
|
|
dc425d7872 | ||
|
|
9182fdc110 | ||
|
|
e83ba5f309 | ||
|
|
9357b79e1d | ||
|
|
fccab23c7e | ||
|
|
4c45b35878 | ||
|
|
ed48a838ce |
46
.github/workflows/generate_solutions_files.yml
vendored
Normal file
46
.github/workflows/generate_solutions_files.yml
vendored
Normal 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
@@ -3,15 +3,12 @@
|
|||||||
|
|
||||||
# 100 numpy exercises
|
# 100 numpy exercises
|
||||||
|
|
||||||
This is a collection of exercises that have been collected in the numpy mailing list, on stack
|
This is a collection of exercises that have been collected in the numpy mailing list, on stack overflow
|
||||||
overflow
|
|
||||||
and in the numpy documentation. The goal of this collection is to offer a quick reference for both old
|
and in the numpy documentation. The goal of this collection is to offer a quick reference for both old
|
||||||
and new
|
and new users but also to provide a set of exercises for those who teach.
|
||||||
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
|
If you find an error or think you've a better way to solve some of them, feel
|
||||||
solve some of them, feel
|
|
||||||
free to open an issue at <https://github.com/rougier/numpy-100>.
|
free to open an issue at <https://github.com/rougier/numpy-100>.
|
||||||
File automatically generated. See the documentation to update questions/answers/hints programmatically.
|
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? (★★☆)
|
#### 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) (★★☆)
|
#### 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)) (★★☆)
|
#### 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? (★★☆)
|
#### 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 (★★☆)
|
#### 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? (★★☆)
|
#### 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? (★★★)
|
#### 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? (★★★)
|
#### 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])? (★★★)
|
#### 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]]? (★★★)
|
#### 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] (★★★)
|
#### 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)? (★★★)
|
#### 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 (★★★)
|
#### 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? (★★★)
|
#### 91. How to create a record array from a regular array? (★★★)
|
||||||
|
|
||||||
|
|||||||
@@ -3,15 +3,12 @@
|
|||||||
|
|
||||||
# 100 numpy exercises
|
# 100 numpy exercises
|
||||||
|
|
||||||
This is a collection of exercises that have been collected in the numpy mailing list, on stack
|
This is a collection of exercises that have been collected in the numpy mailing list, on stack overflow
|
||||||
overflow
|
|
||||||
and in the numpy documentation. The goal of this collection is to offer a quick reference for both old
|
and in the numpy documentation. The goal of this collection is to offer a quick reference for both old
|
||||||
and new
|
and new users but also to provide a set of exercises for those who teach.
|
||||||
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
|
If you find an error or think you've a better way to solve some of them, feel
|
||||||
solve some of them, feel
|
|
||||||
free to open an issue at <https://github.com/rougier/numpy-100>.
|
free to open an issue at <https://github.com/rougier/numpy-100>.
|
||||||
File automatically generated. See the documentation to update questions/answers/hints programmatically.
|
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`
|
`hint: sort`
|
||||||
#### 41. How to sum a small array faster than np.sum? (★★☆)
|
#### 41. How to sum a small array faster than np.sum? (★★☆)
|
||||||
`hint: np.add.reduce`
|
`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`
|
`hint: np.allclose, np.array_equal`
|
||||||
#### 43. Make an array immutable (read-only) (★★☆)
|
#### 43. Make an array immutable (read-only) (★★☆)
|
||||||
`hint: flags.writeable`
|
`hint: flags.writeable`
|
||||||
@@ -140,7 +137,7 @@ np.sqrt(-1) == np.emath.sqrt(-1)
|
|||||||
`hint: np.meshgrid`
|
`hint: np.meshgrid`
|
||||||
#### 47. Given two arrays, X and Y, construct the Cauchy matrix C (Cij =1/(xi - yj)) (★★☆)
|
#### 47. Given two arrays, X and Y, construct the Cauchy matrix C (Cij =1/(xi - yj)) (★★☆)
|
||||||
`hint: np.subtract.outer`
|
`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`
|
`hint: np.iinfo, np.finfo, eps`
|
||||||
#### 49. How to print all the values of an array? (★★☆)
|
#### 49. How to print all the values of an array? (★★☆)
|
||||||
`hint: np.set_printoptions`
|
`hint: np.set_printoptions`
|
||||||
@@ -150,7 +147,7 @@ np.sqrt(-1) == np.emath.sqrt(-1)
|
|||||||
`hint: dtype`
|
`hint: dtype`
|
||||||
#### 52. Consider a random vector with shape (100,2) representing coordinates, find point by point distances (★★☆)
|
#### 52. Consider a random vector with shape (100,2) representing coordinates, find point by point distances (★★☆)
|
||||||
`hint: np.atleast_2d, T, np.sqrt`
|
`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 [:] =`
|
`hint: view and [:] =`
|
||||||
#### 54. How to read the following file? (★★☆)
|
#### 54. How to read the following file? (★★☆)
|
||||||
```
|
```
|
||||||
@@ -191,7 +188,7 @@ np.sqrt(-1) == np.emath.sqrt(-1)
|
|||||||
`hint: np.diag`
|
`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? (★★★)
|
#### 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]`
|
`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]`
|
`hint: array[:, :, None]`
|
||||||
#### 72. How to swap two rows of an array? (★★★)
|
#### 72. How to swap two rows of an array? (★★★)
|
||||||
`hint: array[[]] = array[[]]`
|
`hint: array[[]] = array[[]]`
|
||||||
@@ -209,7 +206,7 @@ np.sqrt(-1) == np.emath.sqrt(-1)
|
|||||||
`No hints provided...`
|
`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])? (★★★)
|
#### 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...`
|
`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`
|
`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]]? (★★★)
|
#### 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)`
|
`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)`
|
`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] (★★★)
|
#### 85. Create a 2D array subclass such that Z[i,j] == Z[j,i] (★★★)
|
||||||
`hint: class method`
|
`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`
|
`hint: np.tensordot`
|
||||||
#### 87. Consider a 16x16 array, how to get the block-sum (block size is 4x4)? (★★★)
|
#### 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)`
|
`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...`
|
`No hints provided...`
|
||||||
#### 89. How to get the n largest values of an array (★★★)
|
#### 89. How to get the n largest values of an array (★★★)
|
||||||
`hint: np.argsort | np.argpartition`
|
`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`
|
`hint: np.indices`
|
||||||
#### 91. How to create a record array from a regular array? (★★★)
|
#### 91. How to create a record array from a regular array? (★★★)
|
||||||
`hint: np.core.records.fromarrays`
|
`hint: np.core.records.fromarrays`
|
||||||
|
|||||||
@@ -3,15 +3,12 @@
|
|||||||
|
|
||||||
# 100 numpy exercises
|
# 100 numpy exercises
|
||||||
|
|
||||||
This is a collection of exercises that have been collected in the numpy mailing list, on stack
|
This is a collection of exercises that have been collected in the numpy mailing list, on stack overflow
|
||||||
overflow
|
|
||||||
and in the numpy documentation. The goal of this collection is to offer a quick reference for both old
|
and in the numpy documentation. The goal of this collection is to offer a quick reference for both old
|
||||||
and new
|
and new users but also to provide a set of exercises for those who teach.
|
||||||
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
|
If you find an error or think you've a better way to solve some of them, feel
|
||||||
solve some of them, feel
|
|
||||||
free to open an issue at <https://github.com/rougier/numpy-100>.
|
free to open an issue at <https://github.com/rougier/numpy-100>.
|
||||||
File automatically generated. See the documentation to update questions/answers/hints programmatically.
|
File automatically generated. See the documentation to update questions/answers/hints programmatically.
|
||||||
|
|
||||||
@@ -41,6 +38,9 @@ print(Z)
|
|||||||
```python
|
```python
|
||||||
Z = np.zeros((10,10))
|
Z = np.zeros((10,10))
|
||||||
print("%d bytes" % (Z.size * Z.itemsize))
|
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? (★☆☆)
|
#### 5. How to get the documentation of the numpy add function from the command line? (★☆☆)
|
||||||
`hint: np.info`
|
`hint: np.info`
|
||||||
@@ -131,7 +131,7 @@ Z = np.ones((5,5))
|
|||||||
Z = np.pad(Z, pad_width=1, mode='constant', constant_values=0)
|
Z = np.pad(Z, pad_width=1, mode='constant', constant_values=0)
|
||||||
print(Z)
|
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
|
||||||
Z[[0, -1], :] = 0
|
Z[[0, -1], :] = 0
|
||||||
print(Z)
|
print(Z)
|
||||||
@@ -205,7 +205,7 @@ color = np.dtype([("r", np.ubyte),
|
|||||||
`hint:`
|
`hint:`
|
||||||
|
|
||||||
```python
|
```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)
|
print(Z)
|
||||||
|
|
||||||
# Alternative solution, in Python 3.5 and above
|
# Alternative solution, in Python 3.5 and above
|
||||||
@@ -399,7 +399,7 @@ print(Z)
|
|||||||
Z = np.arange(10)
|
Z = np.arange(10)
|
||||||
np.add.reduce(Z)
|
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`
|
`hint: np.allclose, np.array_equal`
|
||||||
|
|
||||||
```python
|
```python
|
||||||
@@ -461,7 +461,7 @@ Y = X + 0.5
|
|||||||
C = 1.0 / np.subtract.outer(X, Y)
|
C = 1.0 / np.subtract.outer(X, Y)
|
||||||
print(np.linalg.det(C))
|
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`
|
`hint: np.iinfo, np.finfo, eps`
|
||||||
|
|
||||||
```python
|
```python
|
||||||
@@ -519,7 +519,7 @@ Z = np.random.random((10,2))
|
|||||||
D = scipy.spatial.distance.cdist(Z,Z)
|
D = scipy.spatial.distance.cdist(Z,Z)
|
||||||
print(D)
|
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 [:] =`
|
`hint: view and [:] =`
|
||||||
|
|
||||||
```python
|
```python
|
||||||
@@ -548,7 +548,7 @@ s = StringIO('''1, 2, 3, 4, 5
|
|||||||
|
|
||||||
, , 9,10,11
|
, , 9,10,11
|
||||||
''')
|
''')
|
||||||
Z = np.genfromtxt(s, delimiter=",", dtype=np.int)
|
Z = np.genfromtxt(s, delimiter=",", dtype = int, filling_values = 0)
|
||||||
print(Z)
|
print(Z)
|
||||||
```
|
```
|
||||||
#### 55. What is the equivalent of enumerate for numpy arrays? (★★☆)
|
#### 55. What is the equivalent of enumerate for numpy arrays? (★★☆)
|
||||||
@@ -565,10 +565,18 @@ for index in np.ndindex(Z.shape):
|
|||||||
`hint: np.meshgrid, np.exp`
|
`hint: np.meshgrid, np.exp`
|
||||||
|
|
||||||
```python
|
```python
|
||||||
X, Y = np.meshgrid(np.linspace(-1,1,10), np.linspace(-1,1,10))
|
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
|
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)
|
print(G)
|
||||||
```
|
```
|
||||||
#### 57. How to randomly place p elements in a 2D array? (★★☆)
|
#### 57. How to randomly place p elements in a 2D array? (★★☆)
|
||||||
@@ -615,8 +623,17 @@ print(Z[Z[:,1].argsort()])
|
|||||||
```python
|
```python
|
||||||
# Author: Warren Weckesser
|
# Author: Warren Weckesser
|
||||||
|
|
||||||
|
# null : 0
|
||||||
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())
|
||||||
|
|
||||||
|
# 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 (★★☆)
|
#### 61. Find the nearest value from a given value in an array (★★☆)
|
||||||
`hint: np.abs, argmin, flat`
|
`hint: np.abs, argmin, flat`
|
||||||
@@ -648,7 +665,7 @@ class NamedArray(np.ndarray):
|
|||||||
return obj
|
return obj
|
||||||
def __array_finalize__(self, obj):
|
def __array_finalize__(self, obj):
|
||||||
if obj is None: return
|
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")
|
Z = NamedArray(np.arange(10), "range_10")
|
||||||
print (Z.name)
|
print (Z.name)
|
||||||
@@ -766,7 +783,7 @@ Z0 = np.zeros(len(Z) + (len(Z)-1)*(nz))
|
|||||||
Z0[::nz+1] = Z
|
Z0[::nz+1] = Z
|
||||||
print(Z0)
|
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]`
|
`hint: array[:, :, None]`
|
||||||
|
|
||||||
```python
|
```python
|
||||||
@@ -864,7 +881,27 @@ np.negative(Z, out=Z)
|
|||||||
`No hints provided...`
|
`No hints provided...`
|
||||||
|
|
||||||
```python
|
```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
|
T = P1 - P0
|
||||||
L = (T**2).sum(axis=1)
|
L = (T**2).sum(axis=1)
|
||||||
U = -((P0[:,0]-p[...,0])*T[:,0] + (P0[:,1]-p[...,1])*T[:,1]) / L
|
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
|
D = P0 + U*T - p
|
||||||
return np.sqrt((D**2).sum(axis=1))
|
return np.sqrt((D**2).sum(axis=1))
|
||||||
|
|
||||||
P0 = np.random.uniform(-10,10,(10,2))
|
print(distance_slower(P0, P1, p))
|
||||||
P1 = np.random.uniform(-10,10,(10,2))
|
|
||||||
p = np.random.uniform(-10,10,( 1,2))
|
|
||||||
print(distance(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])? (★★★)
|
#### 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...`
|
`No hints provided...`
|
||||||
@@ -888,8 +922,34 @@ P0 = np.random.uniform(-10, 10, (10,2))
|
|||||||
P1 = np.random.uniform(-10,10,(10,2))
|
P1 = np.random.uniform(-10,10,(10,2))
|
||||||
p = 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]))
|
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`
|
`hint: minimum maximum`
|
||||||
|
|
||||||
```python
|
```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()
|
R_stop = np.maximum(R_start, (R_stop - np.maximum(Z_stop-Zs,0))).tolist()
|
||||||
Z_stop = (np.minimum(Z_stop,Zs)).tolist()
|
Z_stop = (np.minimum(Z_stop,Zs)).tolist()
|
||||||
|
|
||||||
r = [slice(start,stop) for start,stop in zip(R_start,R_stop)]
|
r = tuple([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)]
|
z = tuple([slice(start,stop) for start,stop in zip(Z_start,Z_stop)])
|
||||||
R[r] = Z[z]
|
R[r] = Z[z]
|
||||||
print(Z)
|
print(Z)
|
||||||
print(R)
|
print(R)
|
||||||
@@ -944,7 +1004,8 @@ print(sliding_window_view(Z, window_shape=4))
|
|||||||
|
|
||||||
Z = np.random.uniform(0,1,(10,10))
|
Z = np.random.uniform(0,1,(10,10))
|
||||||
U, S, V = np.linalg.svd(Z) # Singular Value Decomposition
|
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)
|
print(rank)
|
||||||
|
|
||||||
# alternative solution:
|
# alternative solution:
|
||||||
@@ -998,7 +1059,7 @@ S = symetric(np.random.randint(0,10,(5,5)))
|
|||||||
S[2,3] = 42
|
S[2,3] = 42
|
||||||
print(S)
|
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`
|
`hint: np.tensordot`
|
||||||
|
|
||||||
```python
|
```python
|
||||||
@@ -1037,11 +1098,8 @@ k = 4
|
|||||||
windows = np.lib.stride_tricks.sliding_window_view(Z, (k, k))
|
windows = np.lib.stride_tricks.sliding_window_view(Z, (k, k))
|
||||||
S = windows[::k, ::k, ...].sum(axis=(-2, -1))
|
S = windows[::k, ::k, ...].sum(axis=(-2, -1))
|
||||||
|
|
||||||
# Author: Jeff Luo (@Jeff1999)
|
# alternative solution (by @Gattocrucco)
|
||||||
|
S = Z.reshape(4, 4, 4, 4).sum((1, 3))
|
||||||
Z = np.ones((16, 16))
|
|
||||||
k = 4
|
|
||||||
print(sliding_window_view(Z, window_shape=(k, k))[::k, ::k].sum(axis=(-2, -1)))
|
|
||||||
```
|
```
|
||||||
#### 88. How to implement the Game of Life using numpy arrays? (★★★)
|
#### 88. How to implement the Game of Life using numpy arrays? (★★★)
|
||||||
`No hints provided...`
|
`No hints provided...`
|
||||||
@@ -1080,7 +1138,7 @@ print (Z[np.argsort(Z)[-n:]])
|
|||||||
# Fast
|
# Fast
|
||||||
print (Z[np.argpartition(-Z,n)[:n]])
|
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`
|
`hint: np.indices`
|
||||||
|
|
||||||
```python
|
```python
|
||||||
|
|||||||
@@ -3,15 +3,12 @@
|
|||||||
|
|
||||||
# 100 numpy exercises
|
# 100 numpy exercises
|
||||||
|
|
||||||
This is a collection of exercises that have been collected in the numpy mailing list, on stack
|
This is a collection of exercises that have been collected in the numpy mailing list, on stack overflow
|
||||||
overflow
|
|
||||||
and in the numpy documentation. The goal of this collection is to offer a quick reference for both old
|
and in the numpy documentation. The goal of this collection is to offer a quick reference for both old
|
||||||
and new
|
and new users but also to provide a set of exercises for those who teach.
|
||||||
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
|
If you find an error or think you've a better way to solve some of them, feel
|
||||||
solve some of them, feel
|
|
||||||
free to open an issue at <https://github.com/rougier/numpy-100>.
|
free to open an issue at <https://github.com/rougier/numpy-100>.
|
||||||
File automatically generated. See the documentation to update questions/answers/hints programmatically.
|
File automatically generated. See the documentation to update questions/answers/hints programmatically.
|
||||||
|
|
||||||
@@ -41,6 +38,9 @@ print(Z)
|
|||||||
```python
|
```python
|
||||||
Z = np.zeros((10,10))
|
Z = np.zeros((10,10))
|
||||||
print("%d bytes" % (Z.size * Z.itemsize))
|
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? (★☆☆)
|
#### 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)
|
Z = np.pad(Z, pad_width=1, mode='constant', constant_values=0)
|
||||||
print(Z)
|
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
|
||||||
Z[[0, -1], :] = 0
|
Z[[0, -1], :] = 0
|
||||||
print(Z)
|
print(Z)
|
||||||
@@ -205,7 +205,7 @@ color = np.dtype([("r", np.ubyte),
|
|||||||
|
|
||||||
|
|
||||||
```python
|
```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)
|
print(Z)
|
||||||
|
|
||||||
# Alternative solution, in Python 3.5 and above
|
# Alternative solution, in Python 3.5 and above
|
||||||
@@ -399,7 +399,7 @@ print(Z)
|
|||||||
Z = np.arange(10)
|
Z = np.arange(10)
|
||||||
np.add.reduce(Z)
|
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
|
```python
|
||||||
@@ -461,7 +461,7 @@ Y = X + 0.5
|
|||||||
C = 1.0 / np.subtract.outer(X, Y)
|
C = 1.0 / np.subtract.outer(X, Y)
|
||||||
print(np.linalg.det(C))
|
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
|
```python
|
||||||
@@ -519,7 +519,7 @@ Z = np.random.random((10,2))
|
|||||||
D = scipy.spatial.distance.cdist(Z,Z)
|
D = scipy.spatial.distance.cdist(Z,Z)
|
||||||
print(D)
|
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
|
```python
|
||||||
@@ -548,7 +548,7 @@ s = StringIO('''1, 2, 3, 4, 5
|
|||||||
|
|
||||||
, , 9,10,11
|
, , 9,10,11
|
||||||
''')
|
''')
|
||||||
Z = np.genfromtxt(s, delimiter=",", dtype=np.int)
|
Z = np.genfromtxt(s, delimiter=",", dtype = int, filling_values = 0)
|
||||||
print(Z)
|
print(Z)
|
||||||
```
|
```
|
||||||
#### 55. What is the equivalent of enumerate for numpy arrays? (★★☆)
|
#### 55. What is the equivalent of enumerate for numpy arrays? (★★☆)
|
||||||
@@ -565,10 +565,18 @@ for index in np.ndindex(Z.shape):
|
|||||||
|
|
||||||
|
|
||||||
```python
|
```python
|
||||||
X, Y = np.meshgrid(np.linspace(-1,1,10), np.linspace(-1,1,10))
|
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
|
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)
|
print(G)
|
||||||
```
|
```
|
||||||
#### 57. How to randomly place p elements in a 2D array? (★★☆)
|
#### 57. How to randomly place p elements in a 2D array? (★★☆)
|
||||||
@@ -615,8 +623,17 @@ print(Z[Z[:,1].argsort()])
|
|||||||
```python
|
```python
|
||||||
# Author: Warren Weckesser
|
# Author: Warren Weckesser
|
||||||
|
|
||||||
|
# null : 0
|
||||||
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())
|
||||||
|
|
||||||
|
# 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 (★★☆)
|
#### 61. Find the nearest value from a given value in an array (★★☆)
|
||||||
|
|
||||||
@@ -648,7 +665,7 @@ class NamedArray(np.ndarray):
|
|||||||
return obj
|
return obj
|
||||||
def __array_finalize__(self, obj):
|
def __array_finalize__(self, obj):
|
||||||
if obj is None: return
|
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")
|
Z = NamedArray(np.arange(10), "range_10")
|
||||||
print (Z.name)
|
print (Z.name)
|
||||||
@@ -766,7 +783,7 @@ Z0 = np.zeros(len(Z) + (len(Z)-1)*(nz))
|
|||||||
Z0[::nz+1] = Z
|
Z0[::nz+1] = Z
|
||||||
print(Z0)
|
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
|
```python
|
||||||
@@ -864,7 +881,27 @@ np.negative(Z, out=Z)
|
|||||||
|
|
||||||
|
|
||||||
```python
|
```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
|
T = P1 - P0
|
||||||
L = (T**2).sum(axis=1)
|
L = (T**2).sum(axis=1)
|
||||||
U = -((P0[:,0]-p[...,0])*T[:,0] + (P0[:,1]-p[...,1])*T[:,1]) / L
|
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
|
D = P0 + U*T - p
|
||||||
return np.sqrt((D**2).sum(axis=1))
|
return np.sqrt((D**2).sum(axis=1))
|
||||||
|
|
||||||
P0 = np.random.uniform(-10,10,(10,2))
|
print(distance_slower(P0, P1, p))
|
||||||
P1 = np.random.uniform(-10,10,(10,2))
|
|
||||||
p = np.random.uniform(-10,10,( 1,2))
|
|
||||||
print(distance(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])? (★★★)
|
#### 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))
|
P1 = np.random.uniform(-10,10,(10,2))
|
||||||
p = 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]))
|
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
|
```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()
|
R_stop = np.maximum(R_start, (R_stop - np.maximum(Z_stop-Zs,0))).tolist()
|
||||||
Z_stop = (np.minimum(Z_stop,Zs)).tolist()
|
Z_stop = (np.minimum(Z_stop,Zs)).tolist()
|
||||||
|
|
||||||
r = [slice(start,stop) for start,stop in zip(R_start,R_stop)]
|
r = tuple([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)]
|
z = tuple([slice(start,stop) for start,stop in zip(Z_start,Z_stop)])
|
||||||
R[r] = Z[z]
|
R[r] = Z[z]
|
||||||
print(Z)
|
print(Z)
|
||||||
print(R)
|
print(R)
|
||||||
@@ -944,7 +1004,8 @@ print(sliding_window_view(Z, window_shape=4))
|
|||||||
|
|
||||||
Z = np.random.uniform(0,1,(10,10))
|
Z = np.random.uniform(0,1,(10,10))
|
||||||
U, S, V = np.linalg.svd(Z) # Singular Value Decomposition
|
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)
|
print(rank)
|
||||||
|
|
||||||
# alternative solution:
|
# alternative solution:
|
||||||
@@ -998,7 +1059,7 @@ S = symetric(np.random.randint(0,10,(5,5)))
|
|||||||
S[2,3] = 42
|
S[2,3] = 42
|
||||||
print(S)
|
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
|
```python
|
||||||
@@ -1037,11 +1098,8 @@ k = 4
|
|||||||
windows = np.lib.stride_tricks.sliding_window_view(Z, (k, k))
|
windows = np.lib.stride_tricks.sliding_window_view(Z, (k, k))
|
||||||
S = windows[::k, ::k, ...].sum(axis=(-2, -1))
|
S = windows[::k, ::k, ...].sum(axis=(-2, -1))
|
||||||
|
|
||||||
# Author: Jeff Luo (@Jeff1999)
|
# alternative solution (by @Gattocrucco)
|
||||||
|
S = Z.reshape(4, 4, 4, 4).sum((1, 3))
|
||||||
Z = np.ones((16, 16))
|
|
||||||
k = 4
|
|
||||||
print(sliding_window_view(Z, window_shape=(k, k))[::k, ::k].sum(axis=(-2, -1)))
|
|
||||||
```
|
```
|
||||||
#### 88. How to implement the Game of Life using numpy arrays? (★★★)
|
#### 88. How to implement the Game of Life using numpy arrays? (★★★)
|
||||||
|
|
||||||
@@ -1080,7 +1138,7 @@ print (Z[np.argsort(Z)[-n:]])
|
|||||||
# Fast
|
# Fast
|
||||||
print (Z[np.argpartition(-Z,n)[:n]])
|
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
|
```python
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
"cells": [
|
"cells": [
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"id": "a194d42e",
|
"id": "94b10be0",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"# 100 numpy exercises\n",
|
"# 100 numpy exercises\n",
|
||||||
@@ -18,7 +18,7 @@
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"id": "a7fd49f7",
|
"id": "1d0b9900",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"source": [
|
||||||
"File automatically generated. See the documentation to update questions/answers/hints programmatically."
|
"File automatically generated. See the documentation to update questions/answers/hints programmatically."
|
||||||
@@ -26,17 +26,17 @@
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "markdown",
|
"cell_type": "markdown",
|
||||||
"id": "b702d5a2",
|
"id": "21313ae9",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"source": [
|
"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."
|
"`hint(n)` and the answer with `answer(n)`, where n is the number of the picked question."
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"cell_type": "code",
|
"cell_type": "code",
|
||||||
"execution_count": null,
|
"execution_count": null,
|
||||||
"id": "da60e1d0",
|
"id": "c4ad3a14",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
@@ -46,7 +46,7 @@
|
|||||||
{
|
{
|
||||||
"cell_type": "code",
|
"cell_type": "code",
|
||||||
"execution_count": null,
|
"execution_count": null,
|
||||||
"id": "9fb544fe",
|
"id": "13bdf6d0",
|
||||||
"metadata": {},
|
"metadata": {},
|
||||||
"outputs": [],
|
"outputs": [],
|
||||||
"source": [
|
"source": [
|
||||||
|
|||||||
@@ -19,5 +19,4 @@ This work is licensed under the MIT license.
|
|||||||
|
|
||||||
### Variants in Other Languages
|
### Variants in Other Languages
|
||||||
|
|
||||||
#### Julia
|
- **Julia**: [100 Julia Exercises](https://github.com/RoyiAvital/Julia100Exercises).
|
||||||
- [100 Julia Exercises](https://github.com/RoyiAvital/Julia100Exercises).
|
|
||||||
|
|||||||
@@ -108,7 +108,7 @@ def create_markdown(destination_filename='100_Numpy_exercises', with_hints=False
|
|||||||
|
|
||||||
# Add questions (and hint or answers if required)
|
# Add questions (and hint or answers if required)
|
||||||
for n in range(1, 101):
|
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:
|
if with_hints:
|
||||||
mdfile.write(f"`{QHA[f'h{n}']}`")
|
mdfile.write(f"`{QHA[f'h{n}']}`")
|
||||||
if with_solutions:
|
if with_solutions:
|
||||||
|
|||||||
@@ -1,5 +1,3 @@
|
|||||||
numpy==1.17.4
|
numpy
|
||||||
pandas==0.25.3
|
mdutils
|
||||||
jupyter==1.0.0
|
nbformat
|
||||||
jupyterthemes==0.20.0
|
|
||||||
mdutils==1.0.0
|
|
||||||
|
|||||||
1
runtime.txt
Normal file
1
runtime.txt
Normal file
@@ -0,0 +1 @@
|
|||||||
|
python-3.7.17
|
||||||
@@ -37,6 +37,9 @@ hint: size, itemsize
|
|||||||
Z = np.zeros((10,10))
|
Z = np.zeros((10,10))
|
||||||
print("%d bytes" % (Z.size * Z.itemsize))
|
print("%d bytes" % (Z.size * Z.itemsize))
|
||||||
|
|
||||||
|
# Simpler alternative
|
||||||
|
print("%d bytes" % Z.nbytes)
|
||||||
|
|
||||||
< q5
|
< q5
|
||||||
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? (★☆☆)
|
||||||
|
|
||||||
@@ -162,7 +165,7 @@ Z = np.ones((5,5))
|
|||||||
Z = np.pad(Z, pad_width=1, mode='constant', constant_values=0)
|
Z = np.pad(Z, pad_width=1, mode='constant', constant_values=0)
|
||||||
print(Z)
|
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
|
||||||
Z[[0, -1], :] = 0
|
Z[[0, -1], :] = 0
|
||||||
print(Z)
|
print(Z)
|
||||||
@@ -260,7 +263,7 @@ Multiply a 5x3 matrix by a 3x2 matrix (real matrix product) (★☆☆)
|
|||||||
hint:
|
hint:
|
||||||
|
|
||||||
< a24
|
< 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)
|
print(Z)
|
||||||
|
|
||||||
# Alternative solution, in Python 3.5 and above
|
# Alternative solution, in Python 3.5 and above
|
||||||
@@ -506,7 +509,7 @@ Z = np.arange(10)
|
|||||||
np.add.reduce(Z)
|
np.add.reduce(Z)
|
||||||
|
|
||||||
< q42
|
< 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
|
< h42
|
||||||
hint: np.allclose, np.array_equal
|
hint: np.allclose, np.array_equal
|
||||||
@@ -586,7 +589,7 @@ C = 1.0 / np.subtract.outer(X, Y)
|
|||||||
print(np.linalg.det(C))
|
print(np.linalg.det(C))
|
||||||
|
|
||||||
< q48
|
< 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
|
< h48
|
||||||
hint: np.iinfo, np.finfo, eps
|
hint: np.iinfo, np.finfo, eps
|
||||||
@@ -659,7 +662,7 @@ D = scipy.spatial.distance.cdist(Z,Z)
|
|||||||
print(D)
|
print(D)
|
||||||
|
|
||||||
< q53
|
< 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
|
< h53
|
||||||
hint: view and [:] =
|
hint: view and [:] =
|
||||||
@@ -693,7 +696,7 @@ s = StringIO('''1, 2, 3, 4, 5
|
|||||||
|
|
||||||
, , 9,10,11
|
, , 9,10,11
|
||||||
''')
|
''')
|
||||||
Z = np.genfromtxt(s, delimiter=",", dtype=np.int)
|
Z = np.genfromtxt(s, delimiter=",", dtype = int, filling_values = 0)
|
||||||
print(Z)
|
print(Z)
|
||||||
|
|
||||||
< q55
|
< q55
|
||||||
@@ -716,10 +719,18 @@ Generate a generic 2D Gaussian-like array (★★☆)
|
|||||||
hint: np.meshgrid, np.exp
|
hint: np.meshgrid, np.exp
|
||||||
|
|
||||||
< a56
|
< a56
|
||||||
X, Y = np.meshgrid(np.linspace(-1,1,10), np.linspace(-1,1,10))
|
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
|
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)
|
print(G)
|
||||||
|
|
||||||
< q57
|
< q57
|
||||||
@@ -969,7 +980,7 @@ Z0[::nz+1] = Z
|
|||||||
print(Z0)
|
print(Z0)
|
||||||
|
|
||||||
< q71
|
< 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
|
< h71
|
||||||
hint: array[:, :, None]
|
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...
|
No hints provided...
|
||||||
|
|
||||||
< a78
|
< 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
|
T = P1 - P0
|
||||||
L = (T**2).sum(axis=1)
|
L = (T**2).sum(axis=1)
|
||||||
U = -((P0[:,0]-p[...,0])*T[:,0] + (P0[:,1]-p[...,1])*T[:,1]) / L
|
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
|
D = P0 + U*T - p
|
||||||
return np.sqrt((D**2).sum(axis=1))
|
return np.sqrt((D**2).sum(axis=1))
|
||||||
|
|
||||||
P0 = np.random.uniform(-10,10,(10,2))
|
print(distance_slower(P0, P1, p))
|
||||||
P1 = np.random.uniform(-10,10,(10,2))
|
|
||||||
p = np.random.uniform(-10,10,( 1,2))
|
|
||||||
print(distance(P0, P1, p))
|
|
||||||
|
|
||||||
< q79
|
< 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])? (★★★)
|
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))
|
p = np.random.uniform(-10, 10, (10,2))
|
||||||
print(np.array([distance(P0,P1,p_i) for p_i in p]))
|
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
|
< 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
|
< h80
|
||||||
hint: minimum maximum
|
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()
|
R_stop = np.maximum(R_start, (R_stop - np.maximum(Z_stop-Zs,0))).tolist()
|
||||||
Z_stop = (np.minimum(Z_stop,Zs)).tolist()
|
Z_stop = (np.minimum(Z_stop,Zs)).tolist()
|
||||||
|
|
||||||
r = [slice(start,stop) for start,stop in zip(R_start,R_stop)]
|
r = tuple([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)]
|
z = tuple([slice(start,stop) for start,stop in zip(Z_start,Z_stop)])
|
||||||
R[r] = Z[z]
|
R[r] = Z[z]
|
||||||
print(Z)
|
print(Z)
|
||||||
print(R)
|
print(R)
|
||||||
@@ -1182,7 +1236,8 @@ hint: np.linalg.svd, np.linalg.matrix_rank
|
|||||||
|
|
||||||
Z = np.random.uniform(0,1,(10,10))
|
Z = np.random.uniform(0,1,(10,10))
|
||||||
U, S, V = np.linalg.svd(Z) # Singular Value Decomposition
|
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)
|
print(rank)
|
||||||
|
|
||||||
# alternative solution:
|
# alternative solution:
|
||||||
@@ -1246,7 +1301,7 @@ S[2,3] = 42
|
|||||||
print(S)
|
print(S)
|
||||||
|
|
||||||
< q86
|
< 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
|
< h86
|
||||||
hint: np.tensordot
|
hint: np.tensordot
|
||||||
@@ -1290,11 +1345,8 @@ k = 4
|
|||||||
windows = np.lib.stride_tricks.sliding_window_view(Z, (k, k))
|
windows = np.lib.stride_tricks.sliding_window_view(Z, (k, k))
|
||||||
S = windows[::k, ::k, ...].sum(axis=(-2, -1))
|
S = windows[::k, ::k, ...].sum(axis=(-2, -1))
|
||||||
|
|
||||||
# Author: Jeff Luo (@Jeff1999)
|
# alternative solution (by @Gattocrucco)
|
||||||
|
S = Z.reshape(4, 4, 4, 4).sum((1, 3))
|
||||||
Z = np.ones((16, 16))
|
|
||||||
k = 4
|
|
||||||
print(sliding_window_view(Z, window_shape=(k, k))[::k, ::k].sum(axis=(-2, -1)))
|
|
||||||
|
|
||||||
< q88
|
< q88
|
||||||
How to implement the Game of Life using numpy arrays? (★★★)
|
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]])
|
print (Z[np.argpartition(-Z,n)[:n]])
|
||||||
|
|
||||||
< q90
|
< 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
|
< h90
|
||||||
hint: np.indices
|
hint: np.indices
|
||||||
|
|||||||
@@ -15,11 +15,11 @@ File automatically generated. See the documentation to update questions/answers/
|
|||||||
|
|
||||||
|
|
||||||
< jupyter_instruction
|
< 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.
|
answer or an hint with `hint(n)` or `answer(n)` for `n` question number.
|
||||||
|
|
||||||
|
|
||||||
< jupyter_instruction_rand
|
< 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.
|
`hint(n)` and the answer with `answer(n)`, where n is the number of the picked question.
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user