Numpy - Exercises¶
Here is a series of tests to check your knowledge in Numpy. The goal is for this library and the vectorized programming it implies to become natural. You should forget about classic programming with loops (do not use a for
loop or anything else in this notebook except for list comprehension).
Functions should never modify their arguments.
The exercises indicate the number of lines in the answer. This includes the function header when there is one.
Remember to test your results.
import numpy as np
rand = np.random.RandomState(123)
A = np.arange(12).reshape(3,4)
B = rand.randint(-10, 10, size=(5,5))
print(A, '\n')
print(B)
[[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11]] [[ 3 -8 -8 -4 7] [ 9 0 -9 -10 7] [ 5 -1 -10 4 -10] [ 5 9 4 -6 -10] [ 6 -6 7 -7 -8]]
array([[ 1, 2, 3, 4, 5], [ 6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25]])
def norm(v):
Sub-Matrix¶
Extract the sub-matrix of size (n-2)x(m-2) that removes the borders of the nxm matrix A.
2 lines
def submat(A):
Random Vector¶
Create a function that takes a size n and returns a random integer vector of size n between -a and +a and centered as close as possible to 0.
3 lines
def rand_vec(n, a):
Trace¶
Return the trace of a matrix without using the trace
function (you have to find the missing elements yourself).
2 lines
def trace(A):
Matrix of Multiples of 3¶
Round the given matrix to the nearest multiple of 3 (for each value).
2 lines
def round3(A):
def nb9(A):
Column with the Smallest Average¶
Return the index of the column of a matrix with the smallest average.
2 lines
def min_col_mean(A):
ChessSum¶
We consider the matrix as a chessboard with alternating white and black squares. The square at [0,0] is black. Calculate the sum of the values on the white squares.
2 lines
def chess_sum(A):
2 Minimums¶
Return the 2 smallest values of a matrix using a method with linear complexity. Note that if the matrix has its minimum value duplicated, the answer is twice this minimum value.
6 lines
def mins(A):
def sort_lines(A):
Unique Values¶
Provide the list of unique values (appearing only once) in a numpy array (the unique
function will be useful).
3 lines
def val_unique(A):
Magic Tensor¶
Construct a 3D tensor of size nxnxn using n times the first n² integers and such that the sum of the elements of each plane (slice) is always the same.
3 lines
def mk_magic_tensor(n):
Tensor Slices¶
Extract all the slices of a 3D tensor. We return a list of arrays.
5 lines (2 lines with the take
function)
def extract_planes(T):