<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<jupyter_output><empty_output><jupyter_text>2. Print the numpy version and the configuration (★☆☆)<jupyter_code>answer(1)<jupyter_output>import numpy as np<jupyter_text>3. Create a null vector of size 10 (★☆☆)<jupyter_code>np.zeros(5, dtype='float')<jupyter_output><empty_output><jupyter_text>4. How to find the memory size of any array (★☆☆)<jupyter_code>array = np.zeros(5, dtype="float")
array.itemsize * array.size<jupyter_output><empty_output><jupyter_text>5. How to get the documentation of the numpy add function from the command line? (★☆☆)<jupyter_code>np.info(np.zeros)<jupyter_output>zeros(shape, dtype=float, order='C', *, like=None)

Return a new array of given shape and type, filled with zeros.

Parameters
----------
shape : int or tuple of ints
    Shape of the new array, e.g., ``(2, 3)`` or ``2``.
dtype : data-type, optional
    The desired data-type for the array, e.g., `numpy.int8`.  Default is
    `numpy.float64`.
order : {'C', 'F'}, optional, default: 'C'
    Whether to store multi-dimensional data in row-major
    (C-style) or column-major (Fortran-style) order in
    memory.
like : array_like
    Reference object to allow the creation of arrays which are not
    NumPy arrays. If an array-like passed in as ``like`` supports
    the ``__array_function__`` protocol, the result will be defined
    by it. In this case, it ensures the creation of an array object
    compatible with that passed in via this argument.

    .. note::
        The ``like`` keyword is an experimental feature pending on
        acceptance of :ref:`NEP 35 <NEP35>`.

    .. versionadded:[...]<jupyter_text>6. Create a null vector of size 10 but the fifth value which is 1 (★☆☆)<jupyter_code>array = np.zeros(10) 
array[4] = 1
array<jupyter_output><empty_output><jupyter_text>7. Create a vector with values ranging from 10 to 49 (★☆☆)<jupyter_code>array = np.arange(10,50)<jupyter_output><empty_output><jupyter_text>8. Reverse a vector (first element becomes last) (★☆☆)<jupyter_code>array[::-1]<jupyter_output><empty_output><jupyter_text>9. Create a 3x3 matrix with values ranging from 0 to 8 (★☆☆)<jupyter_code>np.arange(9).reshape((3,3))<jupyter_output><empty_output><jupyter_text>10. Find indices of non-zero elements from [1,2,0,0,4,0] (★☆☆)<jupyter_code>a = [1,2,0,0,4,0]
np.nonzero(a)<jupyter_output><empty_output><jupyter_text>11. Create a 3x3 identity matrix (★☆☆)<jupyter_code>np.eye(8)<jupyter_output><empty_output><jupyter_text>12. Create a 3x3x3 array with random values (★☆☆)<jupyter_code>a = np.random.random(27).reshape((3,3,3))
a.shape<jupyter_output><empty_output><jupyter_text>13. Create a 10x10 array with random values and find the minimum and maximum values (★☆☆)<jupyter_code>np.random.random(100).reshape((10,10)).max()<jupyter_output><empty_output><jupyter_text>14. Create a random vector of size 30 and find the mean value (★☆☆)<jupyter_code>np.random.random(30).mean()<jupyter_output><empty_output><jupyter_text>15. Create a 2d array with 1 on the border and 0 inside (★☆☆)<jupyter_code>a = np.ones(25).reshape((5,5))
a[1:-1,1:-1] = 0
a<jupyter_output><empty_output><jupyter_text>16. How to add a border (filled with 0's) around an existing array? (★☆☆)<jupyter_code>a = np.random.random(25).reshape((5,5))
np.pad(a, pad_width=1, mode='mean')<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>0 * np.nan
np.nan == np.nan
np.inf > np.nan
np.nan - np.nan
np.nan in set([np.nan])
0.3 == 3 * 0.1<jupyter_output><empty_output><jupyter_text>18. Create a 5x5 matrix with values 1,2,3,4 just below the diagonal (★☆☆)<jupyter_code>Z = np.diag(1+np.arange(4),k=-1)
print(Z)<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>Z = np.zeros((8,8),dtype=int)
print(Z)<jupyter_output>[[0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 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>Z = np.tile( np.array([[0,1],[1,0]]), (4,4))
print(Z)<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>22. Normalize a 5x5 random matrix (★☆☆)<jupyter_code>Z = np.random.random((5,5))
print(Z)<jupyter_output>[[0.41702266 0.13287876 0.64078479 0.74890311 0.47575794]
 [0.27656143 0.23726717 0.26395814 0.32455809 0.5051176 ]
 [0.2268488  0.43631078 0.52661577 0.10526734 0.19445263]
 [0.92991336 0.00524947 0.93654334 0.64389514 0.7219332 ]
 [0.15622405 0.5311287  0.79851603 0.89151105 0.9239061 ]]<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>hint(24)<jupyter_output>hint:<jupyter_text>25. Given a 1D array, negate all elements which are between 3 and 8, in place. (★☆☆)<jupyter_code>Z = np.arange(11)
Z[(3 < Z) & (Z < 8)] *= -1
print(Z)<jupyter_output>[ 0  1  2  3 -4 -5 -6 -7  8  9 10]<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```  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>np.array(0) / np.array(0)<jupyter_output><ipython-input-25-3585dcb7ab9b>:1: RuntimeWarning: invalid value encountered in true_divide
  np.array(0) / np.array(0)<jupyter_text>29. How to round away from zero a float array ? (★☆☆)  30. How to find common values between two arrays? (★☆☆)<jupyter_code>Z1 = np.random.randint(0,10,10)
Z2 = np.random.randint(0,10,10)
print(np.intersect1d(Z1,Z2))<jupyter_output>[0 2 3 4 6 9]<jupyter_text>31. How to ignore all numpy warnings (not recommended)? (★☆☆)<jupyter_code>np.seterr(all="raise")
np.ones(1) / 0<jupyter_output><empty_output><jupyter_text>32. Is the following expressions true? (★☆☆)```pythonnp.sqrt(-1) == np.emath.sqrt(-1)```<jupyter_code>np.sqrt(3) == np.emath.sqrt(3)<jupyter_output><empty_output><jupyter_text>33. How to get the dates of yesterday, today and tomorrow? (★☆☆)<jupyter_code>np.datetime64('today')
np.datetime64('today')+np.timedelta64(1)<jupyter_output><empty_output><jupyter_text>34. How to get all the dates corresponding to the month of July 2016? (★★☆)<jupyter_code>np.arange('2016-07', '2016-08', dtype='datetime64[D]')<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>x = np.ones(10)
y = np.ones(10)
hint(35)
np.add(x, y, out=x)
x<jupyter_output>hint: np.add(out=), np.negative(out=), np.multiply(out=), np.divide(out=)<jupyter_text>36. Extract the integer part of a random array of positive numbers using 4 different methods (★★☆)<jupyter_code>print(np.floor(np.random.uniform(0,10,10)))
print(np.random.uniform(0,10,10).astype(int))
print(np.trunc(np.random.uniform(0,10,10)))<jupyter_output>[8. 7. 8. 6. 7. 4. 7. 3. 5. 7.]
[7 1 2 4 8 8 7 5 2 2]
[6. 0. 7. 1. 4. 9. 9. 5. 3. 7.]
{'fraction_non_alphanumeric': 0.16206221448770938, 'fraction_numerical': 0.10833152055688493, 'mean_word_length': 4.856687898089172, 'pattern_counts': {'":': 0, '<': 132, '<?xml version=': 0, '>': 132, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '35', 'dir': 'jupyter-structured-clean-dedup', 'id': '309233', 'license': 'MIT', 'n_tokens_mistral': 4351, 'n_tokens_neox': 3758, 'n_words': 1007, 'path': '100_Numpy_exercises.ipynb', 'repo_name': 'felixprograms/numpy_problems', 'size': '9203'}