Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixes to questions 2, 9, 18, 31, 35, 44, 52, 56, 66 & 78 #106

Open
wants to merge 11 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion 100_Numpy_exercises.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -564,7 +564,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"#### 36. Extract the integer part of a random array using 5 different methods (★★☆)"
"#### 36. Extract the integer part of a random array of positive numbers using 4 different methods (★★☆)"
]
},
{
Expand Down
2 changes: 1 addition & 1 deletion 100_Numpy_exercises.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ np.sqrt(-1) == np.emath.sqrt(-1)

#### 35. How to compute ((A+B)*(-A/2)) in place (without copy)? (★★☆)

#### 36. Extract the integer part of a random array using 5 different methods (★★☆)
#### 36. Extract the integer part of a random array of positive numbers using 4 different methods (★★☆)

#### 37. Create a 5x5 matrix with row values ranging from 0 to 4 (★★☆)

Expand Down
8 changes: 4 additions & 4 deletions 100_Numpy_exercises_with_hints.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ File automatically generated. See the documentation to update questions/answers/
#### 1. Import the numpy package under the name `np` (★☆☆)
`hint: import … as`
#### 2. Print the numpy version and the configuration (★☆☆)
`hint: np.__version__, np.show_config)`
`hint: np.__version__, np.show_config`
#### 3. Create a null vector of size 10 (★☆☆)
`hint: np.zeros`
#### 4. How to find the memory size of any array (★☆☆)
Expand Down Expand Up @@ -113,8 +113,8 @@ np.sqrt(-1) == np.emath.sqrt(-1)
`hint: np.arange(dtype=datetime64['D'])`
#### 35. How to compute ((A+B)*(-A/2)) in place (without copy)? (★★☆)
`hint: np.add(out=), np.negative(out=), np.multiply(out=), np.divide(out=)`
#### 36. Extract the integer part of a random array using 5 different methods (★★☆)
`hint: %, np.floor, np.ceil, astype, np.trunc`
#### 36. Extract the integer part of a random array of positive numbers using 4 different methods (★★☆)
`hint: %, np.floor, astype, np.trunc`
#### 37. Create a 5x5 matrix with row values ranging from 0 to 4 (★★☆)
`hint: np.arange`
#### 38. Consider a generator function that generates 10 integers and use it to build an array (★☆☆)
Expand All @@ -130,7 +130,7 @@ np.sqrt(-1) == np.emath.sqrt(-1)
#### 43. Make an array immutable (read-only) (★★☆)
`hint: flags.writeable`
#### 44. Consider a random 10x2 matrix representing cartesian coordinates, convert them to polar coordinates (★★☆)
`hint: np.sqrt, np.arctan2`
`hint: np.hypot, np.arctan2`
#### 45. Create random vector of size 10 and replace the maximum value by 0 (★★☆)
`hint: argmax`
#### 46. Create a structured array with `x` and `y` coordinates covering the [0,1]x[0,1] area (★★☆)
Expand Down
40 changes: 20 additions & 20 deletions 100_Numpy_exercises_with_hints_with_solutions.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ File automatically generated. See the documentation to update questions/answers/
import numpy as np
```
#### 2. Print the numpy version and the configuration (★☆☆)
`hint: np.__version__, np.show_config)`
`hint: np.__version__, np.show_config`

```python
print(np.__version__)
Expand Down Expand Up @@ -72,8 +72,8 @@ print(Z)
`hint: reshape`

```python
nz = np.nonzero([1,2,0,0,4,0])
print(nz)
Z = np.arange(9).reshape((3, 3))
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why this change ?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The current solution corresponds to question 10.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My bad... Thanks for fixing it!

print(Z)
```
#### 10. Find indices of non-zero elements from [1,2,0,0,4,0] (★☆☆)
`hint: np.nonzero`
Expand Down Expand Up @@ -151,7 +151,7 @@ print(0.3 == 3 * 0.1)
`hint: np.diag`

```python
Z = np.diag(1+np.arange(4),k=-1)
Z = np.diag(np.arange(1,5),k=-1)
print(Z)
```
#### 19. Create a 8x8 matrix and fill it with a checkerboard pattern (★☆☆)
Expand Down Expand Up @@ -292,8 +292,9 @@ Z = np.ones(1) / 0
_ = np.seterr(**defaults)

# Equivalently with a context manager
nz = np.nonzero([1,2,0,0,4,0])
print(nz)
with np.errstate(all='ignore'):
Z = np.arange(3) / 0
print(Z)
```
#### 32. Is the following expressions true? (★☆☆)
```python
Expand Down Expand Up @@ -323,23 +324,22 @@ print(Z)
`hint: np.add(out=), np.negative(out=), np.multiply(out=), np.divide(out=)`

```python
A = np.ones(3)*1
B = np.ones(3)*2
C = np.ones(3)*3
A = np.ones(3)
B = np.full(3, 2)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I prefer the version with ones (in order to keep it simple)

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Okay, I will rebase and drop commit. Should the C matrix stay as well?

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok


np.add(A,B,out=B)
np.divide(A,2,out=A)
np.negative(A,out=A)
np.multiply(A,B,out=A)
```
#### 36. Extract the integer part of a random array using 5 different methods (★★☆)
`hint: %, np.floor, np.ceil, astype, np.trunc`
#### 36. Extract the integer part of a random array of positive numbers using 4 different methods (★★☆)
`hint: %, np.floor, astype, np.trunc`

```python
Z = np.random.uniform(0,10,10)

print (Z - Z%1)
print (np.floor(Z))
print (np.ceil(Z)-1)
print (Z.astype(int))
print (np.trunc(Z))
```
Expand Down Expand Up @@ -409,12 +409,12 @@ Z.flags.writeable = False
Z[0] = 1
```
#### 44. Consider a random 10x2 matrix representing cartesian coordinates, convert them to polar coordinates (★★☆)
`hint: np.sqrt, np.arctan2`
`hint: np.hypot, np.arctan2`

```python
Z = np.random.random((10,2))
X,Y = Z[:,0], Z[:,1]
R = np.sqrt(X**2+Y**2)
R = np.hypot(Y,X)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Y,X -> X,Y (for consistency)

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The order is such so that it's consistent with the order of arguments in the arctan2 invocation. It's my personal mnemonic, but I will change it if you insist.

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would prefer yes.

T = np.arctan2(Y,X)
print(R)
print(T)
Expand Down Expand Up @@ -493,7 +493,7 @@ print(Z)
```python
Z = np.random.random((10,2))
X,Y = np.atleast_2d(Z[:,0], Z[:,1])
D = np.sqrt( (X-X.T)**2 + (Y-Y.T)**2)
D = np.hypot(X-X.T, Y-Y.T)
print(D)

# Much faster with scipy
Expand Down Expand Up @@ -552,7 +552,7 @@ 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)
D = np.hypot(X, Y)
sigma, mu = 1.0, 0.0
G = np.exp(-( (D-mu)**2 / ( 2.0 * sigma**2 ) ) )
print(G)
Expand Down Expand Up @@ -673,10 +673,10 @@ print(F)
# Author: Nadav Horesh

w,h = 16,16
I = np.random.randint(0,2,(h,w,3)).astype(np.ubyte)
I = np.random.randint(0,2,(h,w,3))
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why did you remove the cast to ubyte ?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In a sufficiently long array, the expected number of different "colors" should be 2**3 == 8. For the solution to work, F must be a matrix of at least 24-bit integers, but this is not what happens on my machine: I[..., 1] * 256 has type np.uint16, and the same happens with I[..., 0] * 256 * 256, leading to overflow. Writing (I[..., 0] * 256) * 256 doesn't solve the problem. A cast to a sufficient wide type has to happen at some point, or the initial cast has to go.

>>> import numpy as np
>>> w, h = 16, 16
>>> I = np.random.randint(0, 2, (h, w, 3))
>>> I2 = I.astype(np.ubyte)
>>> F = I[...,0]*256*256 + I[...,1]*256 +I[...,2]
>>> F2 = I2[...,0]*256*256 + I2[...,1]*256 +I2[...,2]
>>> print(len(np.unique(F)), len(np.unique(F2)))
8 4
>>> print(F.dtype, F2.dtype)
int64 uint16

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok

F = I[...,0]*256*256 + I[...,1]*256 +I[...,2]
n = len(np.unique(F))
print(np.unique(I))
print(n)
```
#### 67. Considering a four dimensions array, how to get sum over the last two axis at once? (★★★)
`hint: sum(axis=(-2,-1))`
Expand Down Expand Up @@ -826,9 +826,9 @@ np.negative(Z, out=Z)
def distance(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
U = ((P0 - p)*T).sum(axis=1) / L
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Did you check this is correct ?

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

?

U = U.reshape(len(U),1)
D = P0 + U*T - p
D = P0 - U*T - p
return np.sqrt((D**2).sum(axis=1))

P0 = np.random.uniform(-10,10,(10,2))
Expand Down
36 changes: 18 additions & 18 deletions 100_Numpy_exercises_with_solutions.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,8 @@ print(Z)


```python
nz = np.nonzero([1,2,0,0,4,0])
print(nz)
Z = np.arange(9).reshape((3, 3))
print(Z)
```
#### 10. Find indices of non-zero elements from [1,2,0,0,4,0] (★☆☆)

Expand Down Expand Up @@ -151,7 +151,7 @@ print(0.3 == 3 * 0.1)


```python
Z = np.diag(1+np.arange(4),k=-1)
Z = np.diag(np.arange(1,5),k=-1)
print(Z)
```
#### 19. Create a 8x8 matrix and fill it with a checkerboard pattern (★☆☆)
Expand Down Expand Up @@ -211,7 +211,7 @@ print(Z)
# Author: Evgeni Burovski

Z = np.arange(11)
Z[(3 < Z) & (Z < 8)] *= -1
Z[(3 < Z) & (Z <= 8)] *= -1
print(Z)
```
#### 26. What is the output of the following script? (★☆☆)
Expand Down Expand Up @@ -292,8 +292,9 @@ Z = np.ones(1) / 0
_ = np.seterr(**defaults)

# Equivalently with a context manager
nz = np.nonzero([1,2,0,0,4,0])
print(nz)
with np.errstate(all='ignore'):
Z = np.arange(3) / 0
print(Z)
```
#### 32. Is the following expressions true? (★☆☆)
```python
Expand Down Expand Up @@ -323,23 +324,22 @@ print(Z)


```python
A = np.ones(3)*1
B = np.ones(3)*2
C = np.ones(3)*3
A = np.ones(3)
B = np.full(3, 2)

np.add(A,B,out=B)
np.divide(A,2,out=A)
np.negative(A,out=A)
np.multiply(A,B,out=A)
```
#### 36. Extract the integer part of a random array using 5 different methods (★★☆)
#### 36. Extract the integer part of a random array of positive numbers using 4 different methods (★★☆)


```python
Z = np.random.uniform(0,10,10)

print (Z - Z%1)
print (np.floor(Z))
print (np.ceil(Z)-1)
print (Z.astype(int))
print (np.trunc(Z))
```
Expand Down Expand Up @@ -414,7 +414,7 @@ Z[0] = 1
```python
Z = np.random.random((10,2))
X,Y = Z[:,0], Z[:,1]
R = np.sqrt(X**2+Y**2)
R = np.hypot(Y,X)
T = np.arctan2(Y,X)
print(R)
print(T)
Expand Down Expand Up @@ -493,7 +493,7 @@ print(Z)
```python
Z = np.random.random((10,2))
X,Y = np.atleast_2d(Z[:,0], Z[:,1])
D = np.sqrt( (X-X.T)**2 + (Y-Y.T)**2)
D = np.hypot(X-X.T, Y-Y.T)
print(D)

# Much faster with scipy
Expand Down Expand Up @@ -552,7 +552,7 @@ 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)
D = np.hypot(X, Y)
sigma, mu = 1.0, 0.0
G = np.exp(-( (D-mu)**2 / ( 2.0 * sigma**2 ) ) )
print(G)
Expand Down Expand Up @@ -673,10 +673,10 @@ print(F)
# Author: Nadav Horesh

w,h = 16,16
I = np.random.randint(0,2,(h,w,3)).astype(np.ubyte)
I = np.random.randint(0,2,(h,w,3))
F = I[...,0]*256*256 + I[...,1]*256 +I[...,2]
n = len(np.unique(F))
print(np.unique(I))
print(n)
```
#### 67. Considering a four dimensions array, how to get sum over the last two axis at once? (★★★)

Expand Down Expand Up @@ -826,9 +826,9 @@ np.negative(Z, out=Z)
def distance(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
U = ((P0 - p)*T).sum(axis=1) / L
U = U.reshape(len(U),1)
D = P0 + U*T - p
D = P0 - U*T - p
return np.sqrt((D**2).sum(axis=1))

P0 = np.random.uniform(-10,10,(10,2))
Expand Down