<jupyter_start><jupyter_text>100 numpy exercisesThis is a collection of exercises that have been collected in the numpy mailing list, on stack overflowand in the numpy documentation. The goal of this collection is to offer a quick reference for both oldand 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, feelfree to open an issue at . File automatically generated. See the documentation to update questions/answers/hints programmatically. Run the `initialize.py` module, then for each question you can query theanswer or an hint with `hint(n)` or `answer(n)` for `n` question number.<jupyter_code>%run initialise.py<jupyter_output><empty_output><jupyter_text>1. Import the numpy package under the name `np` (★☆☆)<jupyter_code>import numpy as np
answer(1)<jupyter_output>import numpy as np<jupyter_text>2. Print the numpy version and the configuration (★☆☆)<jupyter_code>print(np.__version__)<jupyter_output>1.18.1<jupyter_text>3. Create a null vector of size 10 (★☆☆)<jupyter_code>null_vector = np.zeros(10)
print(null_vector)<jupyter_output>[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]<jupyter_text>4. How to find the memory size of any array (★☆☆)<jupyter_code>print('%d bytes ' % (null_vector.size * null_vector.itemsize))<jupyter_output>80 bytes<jupyter_text>5. How to get the documentation of the numpy add function from the command line? (★☆☆)<jupyter_code>np.info(np.add)<jupyter_output>add(x1, x2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj])

Add arguments element-wise.

Parameters
----------
x1, x2 : array_like
    The arrays to be added. If ``x1.shape != x2.shape``, they must be broadcastable to a common shape (which becomes the shape of the output).
out : ndarray, None, or tuple of ndarray and None, optional
    A location into which the result is stored. If provided, it must have
    a shape that the inputs broadcast to. If not provided or None,
    a freshly-allocated array is returned. A tuple (possible only as a
    keyword argument) must have length equal to the number of outputs.
where : array_like, optional
    This condition is broadcast over the input. At locations where the
    condition is True, the `out` array will be set to the ufunc result.
    Elsewhere, the `out` array will retain its original value.
    Note that if an uninitialized `out` array is created via the default
    ``out=None``,[...]<jupyter_text>6. Create a null vector of size 10 but the fifth value which is 1 (★☆☆)<jupyter_code>nv = np.zeros(10)
nv[4] = 1
print(nv)<jupyter_output>[0. 0. 0. 0. 1. 0. 0. 0. 0. 0.]<jupyter_text>7. Create a vector with values ranging from 10 to 49 (★☆☆)<jupyter_code>v = np.arange(10, 50)
print(v)<jupyter_output>[10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49]<jupyter_text>8. Reverse a vector (first element becomes last) (★☆☆)<jupyter_code>v = v[::-1]
print(v)<jupyter_output>[49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26
 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10]<jupyter_text>9. Create a 3x3 matrix with values ranging from 0 to 8 (★☆☆)<jupyter_code>m = np.arange(0,9)
m = m.reshape(3,-1)
print(m)<jupyter_output>[[0 1 2]
 [3 4 5]
 [6 7 8]]<jupyter_text>10. Find indices of non-zero elements from [1,2,0,0,4,0] (★☆☆)<jupyter_code>v = np.array([1,2,0,0,4,0])
print(np.nonzero(v))<jupyter_output>(array([0, 1, 4], dtype=int64),)<jupyter_text>11. Create a 3x3 identity matrix (★☆☆)<jupyter_code>v = np.eye(3)
print(v)<jupyter_output>[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]<jupyter_text>12. Create a 3x3x3 array with random values (★☆☆)<jupyter_code>v = np.random.random(27).reshape(3,3,-1)
# v = np.random.random((3,3,3))
v<jupyter_output><empty_output><jupyter_text>13. Create a 10x10 array with random values and find the minimum and maximum values (★☆☆)<jupyter_code>v = np.random.random((10, 10))
print(v)
# v.max(), v.min()
print(np.max(v))
print(np.min(v))<jupyter_output>[[0.37862127 0.21174227 0.24798405 0.36484221 0.72850737 0.49331288
  0.73236734 0.82919701 0.96792229 0.9389313 ]
 [0.54133644 0.81065223 0.57990798 0.93082022 0.57962531 0.51776199
  0.43419009 0.46937143 0.46450712 0.87940547]
 [0.52752219 0.99872561 0.3536576  0.43044295 0.5409472  0.76021586
  0.86373711 0.7004124  0.59690811 0.62368399]
 [0.73608479 0.11219681 0.03991421 0.2263941  0.54693386 0.08897059
  0.12515429 0.4729882  0.13853258 0.87777499]
 [0.80427494 0.46737226 0.8199438  0.71233701 0.05140089 0.20663177
  0.26675869 0.7192869  0.49985461 0.45699906]
 [0.63625527 0.29001881 0.33701319 0.7728969  0.06183357 0.7604072
  0.93539334 0.38971951 0.19355949 0.90455597]
 [0.92379324 0.94296956 0.5064742  0.40406239 0.16311493 0.91884578
  0.78766238 0.65413921 0.77050716 0.42141367]
 [0.09780512 0.1648282  0.92161584 0.40900746 0.13974744 0.30612647
  0.19607742 0.78133448 0.48897579 0.85496547]
 [0.10104493 0.36310627 0.34034988 0.22754216 0.02110414 0.85158143
  0.75317859 [...]<jupyter_text>14. Create a random vector of size 30 and find the mean value (★☆☆)<jupyter_code>v = np.random.random(30)
print(v.mean())<jupyter_output>0.511724973733518<jupyter_text>15. Create a 2d array with 1 on the border and 0 inside (★☆☆)<jupyter_code>v = np.ones((5,5))
v[1:-1, 1:-1] = 0
print(v)<jupyter_output>[[1. 1. 1. 1. 1.]
 [1. 0. 0. 0. 1.]
 [1. 0. 0. 0. 1.]
 [1. 0. 0. 0. 1.]
 [1. 1. 1. 1. 1.]]<jupyter_text>16. How to add a border (filled with 0's) around an existing array? (★☆☆)<jupyter_code>v = np.ones((5,5))
v = np.pad(v, 1, 'constant', constant_values= 0)
v<jupyter_output><empty_output><jupyter_text>17. What is the result of the following expression? (★☆☆)```python0 * np.nannp.nan == np.nannp.inf > np.nannp.nan - np.nannp.nan in set([np.nan])0.3 == 3 * 0.1```<jupyter_code>print(0 * np.nan)
print(np.nan == np.nan)
print(np.inf < np.nan)
print(np.nan - np.nan)
print(np.nan in set([np.nan]))
print(0.3 == 3 * 0.1)<jupyter_output>nan
False
False
nan
True
False<jupyter_text>18. Create a 5x5 matrix with values 1,2,3,4 just below the diagonal (★☆☆)<jupyter_code>v = np.diag([1, 2, 3, 4], k=-1)
print(v)<jupyter_output>[[0 0 0 0 0]
 [1 0 0 0 0]
 [0 2 0 0 0]
 [0 0 3 0 0]
 [0 0 0 4 0]]<jupyter_text>19. Create a 8x8 matrix and fill it with a checkerboard pattern (★☆☆)<jupyter_code>v = np.ones((8, 8))
v[::2,::2]=0
v[1::2,1::2] = 0
print(v)<jupyter_output>[[0. 1. 0. 1. 0. 1. 0. 1.]
 [1. 0. 1. 0. 1. 0. 1. 0.]
 [0. 1. 0. 1. 0. 1. 0. 1.]
 [1. 0. 1. 0. 1. 0. 1. 0.]
 [0. 1. 0. 1. 0. 1. 0. 1.]
 [1. 0. 1. 0. 1. 0. 1. 0.]
 [0. 1. 0. 1. 0. 1. 0. 1.]
 [1. 0. 1. 0. 1. 0. 1. 0.]]<jupyter_text>20. Consider a (6,7,8) shape array, what is the index (x,y,z) of the 100th element?<jupyter_code>print(np.unravel_index(99, (6, 7, 8)))<jupyter_output>(1, 5, 3)<jupyter_text>21. Create a checkerboard 8x8 matrix using the tile function (★☆☆)<jupyter_code>base = np.array([[0, 1], [1, 0]])
checkboard = np.tile(base, (4, 4))
checkboard<jupyter_output><empty_output><jupyter_text>22. Normalize a 5x5 random matrix (★☆☆)<jupyter_code>vector = np.random.rand(5, 5)
vector = (vector - vector.mean())/vector.std()
vector<jupyter_output><empty_output><jupyter_text>23. Create a custom dtype that describes a color as four unsigned bytes (RGBA) (★☆☆)<jupyter_code>color = np.dtype([
    ("r", np.ubyte),
    ("g", np.ubyte),
    ("b", np.ubyte),
    ("a", np.ubyte)
])<jupyter_output><empty_output><jupyter_text>24. Multiply a 5x3 matrix by a 3x2 matrix (real matrix product) (★☆☆)<jupyter_code>m1 = np.random.rand(5, 3)
m2 = np.random.rand(3, 2)
res = m1.dot(m2)
res<jupyter_output><empty_output><jupyter_text>25. Given a 1D array, negate all elements which are between 3 and 8, in place. (★☆☆)<jupyter_code>vector = np.arange(10)
mask = 3<vector
vector[mask & (vector<8)] *= -1
vector<jupyter_output><empty_output><jupyter_text>26. What is the output of the following script? (★☆☆)```python Author: <NAME>print(sum(range(5),-1))from numpy import *print(sum(range(5),-1))```<jupyter_code>print(sum(range(5),-1))
from numpy import *
print(sum(range(5),-1))<jupyter_output>9
10<jupyter_text>27. Consider an integer vector Z, which of these expressions are legal? (★☆☆)```pythonZ**Z2 > 2Z <- Z1j*ZZ/1/1ZZ```<jupyter_code>Z = np.arange(10)
Z**Z
2 << Z >> 2
Z <- Z
1j*Z
Z/1/1
# Z<Z>Z legal<jupyter_output><empty_output><jupyter_text>28. What are the result of the following expressions?```pythonnp.array(0) / np.array(0)np.array(0) // np.array(0)np.array([np.nan]).astype(int).astype(float)```<jupyter_code>print(np.array(0) / np.array(0))
print(np.array(0) // np.array(0))
print(np.array([np.nan]).astype(int).astype(float))<jupyter_output>nan
0
[-2.14748365e+09]<jupyter_text>29. How to round away from zero a float array ? (★☆☆)<jupyter_code>v = np.random.uniform(-10, 10, 10)
print(v)
print(np.copysign(np.ceil(np.abs(v)), v))<jupyter_output>[-0.95667308  2.54040819 -0.98646448 -6.23848754 -5.78205052  2.82681785
  5.25386216  3.31492879 -8.24229217 -9.46794463]
[ -1.   3.  -1.  -7.  -6.   3.   6.   4.  -9. -10.]<jupyter_text>30. How to find common values between two arrays? (★☆☆)<jupyter_code>v1 = np.random.randint(1, 10, 5)
v2 = np.random.randint(1, 10, 4)
intersect = np.intersect1d(v1, v2) # get intersect v1, v2
print('v1 : ', v1)
print('v2 : ', v2)
intersect<jupyter_output>v1 :  [9 5 1 3 7]
v2 :  [3 2 1 2]<jupyter_text>31. How to ignore all numpy warnings (not recommended)? (★☆☆)<jupyter_code>answer(31)<jupyter_output># Suicide mode on
defaults = np.seterr(all="ignore")
Z = np.ones(1) / 0

# Back to sanity
_ = np.seterr(**defaults)

# Equivalently with a context manager
with np.errstate(all="ignore"):
    np.arange(3) / 0<jupyter_text>32. Is the following expressions true? (★☆☆)```pythonnp.sqrt(-1) == np.emath.sqrt(-1)```<jupyter_code>np.sqrt(-1) == np.emath.sqrt(-1)
print(np.sqrt(-1))
print(np.emath.sqrt(-1))
# sqrt => nan
# emath => 1j<jupyter_output>nan
1j<jupyter_text>33. How to get the dates of yesterday, today and tomorrow? (★☆☆)<jupyter_code>today = np.datetime64('today', 'D')
yesterday = today - np.timedelta64(1, 'D')
tomorrow = today + np.timedelta64(1, 'D')
print(f'today : {today}')
print(f'yesterday : {yesterday}')
print(f'tomorrow : {tomorrow}')<jupyter_output>today : 2020-12-14
yesterday : 2020-12-13
tomorrow : 2020-12-15<jupyter_text>34. How to get all the dates corresponding to the month of July 2016? (★★☆)<jupyter_code>date = np.arange('2016-07-01', '2016-08-01', dtype='datetime64[D]')
print(date)<jupyter_output>['2016-07-01' '2016-07-02' '2016-07-03' '2016-07-04' '2016-07-05'
 '2016-07-06' '2016-07-07' '2016-07-08' '2016-07-09' '2016-07-10'
 '2016-07-11' '2016-07-12' '2016-07-13' '2016-07-14' '2016-07-15'
 '2016-07-16' '2016-07-17' '2016-07-18' '2016-07-19' '2016-07-20'
 '2016-07-21' '2016-07-22' '2016-07-23' '2016-07-24' '2016-07-25'
 '2016-07-26' '2016-07-27' '2016-07-28' '2016-07-29' '2016-07-30'
 '2016-07-31']<jupyter_text>35. How to compute ((A+B)*(-A/2)) in place (without copy)? (★★☆)<jupyter_code>A = np.ones(3)*1
B = np.ones(3)*2

np.add(A,B,out=B)
np.negative(A,out=A)
np.divide(A,2,out=A)
np.multiply(B,A,out=A)
A<jupyter_output><empty_output><jupyter_text>36. Extract the integer part of a random array of positive numbers using 4 different methods (★★☆)<jupyter_code>V = np.random.uniform(0, 10, 10)
print(V.astype(int))
print(np.ceil(V))
print(np.floor(V))
print(V-V%1)<jupyter_output>[7 2 8 5 9 2 7 6 8 0]
[ 8.  3.  9.  6. 10.  3.  8.  7.  9.  1.]
[7. 2. 8. 5. 9. 2. 7. 6. 8. 0.]
[7. 2. 8. 5. 9. 2. 7. 6. 8. 0.]<jupyter_text>37. Create a 5x5 matrix with row values ranging from 0 to 4 (★★☆)<jupyter_code>V = np.zeros((5, 5))
V += np.arange(0, 5)
V<jupyter_output><empty_output><jupyter_text>38. Consider a generator function that generates 10 integers and use it to build an array (★☆☆)<jupyter_code>def generator():
    for i in range(10):
        yield i
V = np.fromiter(generator(), float)
V<jupyter_output><empty_output><jupyter_text>39. Create a vector of size 10 with values ranging from 0 to 1, both excluded (★★☆)<jupyter_code>V = np.linspace(0, 1,11, endpoint=False)
V[1:]<jupyter_output><empty_output><jupyter_text>40. Create a random vector of size 10 and sort it (★★☆)<jupyter_code>V = np.random.random(10)
np.sort(V)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.16756053957419145, 'fraction_numerical': 0.15667154233707134, 'mean_word_length': 4.385995623632385, 'pattern_counts': {'":': 0, '<': 147, '<?xml version=': 0, '>': 146, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 3, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '41', 'dir': 'jupyter-structured-clean-dedup', 'id': '385011', 'license': 'MIT', 'n_tokens_mistral': 6474, 'n_tokens_neox': 5278, 'n_words': 1397, 'path': '100_Numpy_exercises.ipynb', 'repo_name': 'Gun1Yun/numpy-100', 'size': '12315'}