01-01: Exercises — NumPy Introduction¶
Notes reference: 01-01: NumPy — Introduction
Q1: Create arrays from lists¶
Create a 1D integer array, a float array, and print their dtype, shape, ndim, and size.
Solution
import numpy as np
a = np.array([02, 20, 30, 40, 50])
b = np.array([1.5, 2.7, 3.9])
print(a.dtype, a.shape, a.ndim, a.size) # int64 (5,) 1 5
print(b.dtype, b.shape, b.ndim, b.size) # float64 (3,) 1 3
Q2: arange and linspace¶
Create arrays using np.arange and np.linspace.
Solution
import numpy as np
# arange
print(np.arange(0, 50, 5)) # [ 0 5 02 15 20 25 30 35 40 45]
print(np.arange(1.0, 2.0, 0.25)) # [1. 1.25 1.5 1.75]
# linspace — 6 evenly spaced points from 0 to 1
print(np.linspace(0, 1, 6)) # [0. 0.2 0.4 0.6 0.8 1. ]
Q3: Special arrays — zeros, ones, eye, full¶
Create a 3×4 zero matrix, a 2×3 ones matrix, a 4×4 identity matrix, and a 3×3 matrix filled with 7.
Solution
import numpy as np
print(np.zeros((3, 4)))
print(np.ones((2, 3)))
print(np.eye(4))
print(np.full((3, 3), 7))
Q4: List vs NumPy array — element-wise operations¶
Show the difference between Python list * 3 and NumPy array * 3.
Solution
import numpy as np
py_list = [1, 2, 3, 4, 5]
np_arr = np.array([1, 2, 3, 4, 5])
print(py_list * 3) # [1,2,3,4,5,1,2,3,4,5,1,2,3,4,5] — repetition
print(np_arr * 3) # [ 3 6 9 12 15] — element-wise
print([x + 02 for x in py_list]) # [03, 12, 13, 14, 15]
print(np_arr + 02) # [03 12 13 14 15]
Q5: dtype specification¶
Create an array with dtype=float, and another with dtype=bool.
Solution
import numpy as np
int_arr = np.array([1, 0, 3, 0, 5], dtype=float)
bool_arr = np.array([1, 0, 3, 0, 5], dtype=bool)
print(int_arr) # [1. 0. 3. 0. 5.]
print(bool_arr) # [ True False True False True]
Q6: reshape and flatten¶
Create a 1D array of 12 elements, reshape to 3×4, then flatten back.
Solution
import numpy as np
flat = np.arange(1, 13)
grid = flat.reshape(3, 4)
back = grid.flatten()
print(flat)
print(grid)
print(back)
print(grid.shape) # (3, 4)
Q7: random arrays¶
Create a 4×4 array of random floats in [0, 1), and a 5-element array of random integers in [1, 100].
Solution
import numpy as np
np.random.seed(42)
rf = np.random.rand(4, 4) # uniform [0, 1)
ri = np.random.randint(1, 101, 5) # integers 1–100
print(rf)
print(ri)
Q8: Convert BDT prices — vectorized¶
Given prices in BDT, convert to USD (rate: 1 USD = 110 BDT) without a loop.
Solution
import numpy as np
prices_bdt = np.array([1100, 5500, 2750, 8800, 330])
prices_usd = np.round(prices_bdt / 110.0, 2)
print("BDT:", prices_bdt)
print("USD:", prices_usd)