{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# \u2705 NumPy Practice Exercise 1: Complete Solutions & Explanations\n", "\n", "Here are the complete, step-by-step solutions for the **20 problems** in `02_numpy_exercise_1.ipynb`.\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 1: Import NumPy and Check Version\n", "\n", "**Question:** Import NumPy using the standard alias `np` and print the installed version.\n" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "NumPy version: 2.5.3\n" ] } ], "source": [ "import numpy as np\n", "print(\"NumPy version:\", np.__version__)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 2: Create a 1D Array with Integer Range\n", "\n", "**Question:** Create a 1D array of integers from 10 to 49 (inclusive).\n" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Shape: (40,)\n", "First 5: [10 11 12 13 14]\n", "Last 5: [45 46 47 48 49]\n" ] } ], "source": [ "arr = np.arange(10, 50)\n", "print(\"Shape:\", arr.shape)\n", "print(\"First 5:\", arr[:5])\n", "print(\"Last 5:\", arr[-5:])\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 3: Reverse an Array\n", "\n", "**Question:** Reverse the 1D array created in Problem 2 using slicing (no loops or functions).\n" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "First 5 of reversed: [49 48 47 46 45]\n", "Last 5 of reversed: [14 13 12 11 10]\n" ] } ], "source": [ "arr = np.arange(10, 50)\n", "reversed_arr = arr[::-1]\n", "print(\"First 5 of reversed:\", reversed_arr[:5])\n", "print(\"Last 5 of reversed:\", reversed_arr[-5:])\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 4: Create an Identity Matrix with Specific Dtype\n", "\n", "**Question:** Create a 3x3 identity matrix where each element is a 32-bit floating point (`float32`).\n" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[1. 0. 0.]\n", " [0. 1. 0.]\n", " [0. 0. 1.]]\n", "dtype: float32\n" ] } ], "source": [ "identity = np.eye(3, dtype=np.float32)\n", "print(identity)\n", "print(\"dtype:\", identity.dtype)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 5: Evenly Spaced Points (Linspace)\n", "\n", "**Question:** Create a 1D array of 30 evenly spaced numbers between 0 and 1 (inclusive). Print the step size between consecutive elements.\n" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0. 0.03448276 0.06896552 0.10344828 0.13793103 0.17241379\n", " 0.20689655 0.24137931 0.27586207 0.31034483 0.34482759 0.37931034\n", " 0.4137931 0.44827586 0.48275862 0.51724138 0.55172414 0.5862069\n", " 0.62068966 0.65517241 0.68965517 0.72413793 0.75862069 0.79310345\n", " 0.82758621 0.86206897 0.89655172 0.93103448 0.96551724 1. ]\n", "Step size between elements: 0.034482758620689655\n" ] } ], "source": [ "pts, step = np.linspace(0, 1, 30, retstep=True)\n", "print(pts)\n", "print(\"Step size between elements:\", step)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 6: Construct a Diagonal Matrix with Offset\n", "\n", "**Question:** Create a 5x5 matrix with values `[1, 2, 3, 4]` positioned immediately below the main diagonal (offset k = -1).\n" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[[0 0 0 0 0]\n", " [1 0 0 0 0]\n", " [0 2 0 0 0]\n", " [0 0 3 0 0]\n", " [0 0 0 4 0]]\n" ] } ], "source": [ "diag_mat = np.diag([1, 2, 3, 4], k=-1)\n", "print(diag_mat)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 7: Standard Normal Matrix & Aggregate Statistics\n", "\n", "**Question:** Using `np.random.default_rng(42)`, generate an 8x8 matrix drawn from a standard normal distribution. Compute and print its:\n", "- Minimum value\n", "- Maximum value\n", "- Mean\n", "- Standard Deviation\n" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Min: -1.9510\n", "Max: 2.1416\n", "Mean: 0.0414\n", "Std: 0.7894\n" ] } ], "source": [ "rng = np.random.default_rng(42)\n", "mat = rng.standard_normal((8, 8))\n", "print(f\"Min: {mat.min():.4f}\")\n", "print(f\"Max: {mat.max():.4f}\")\n", "print(f\"Mean: {mat.mean():.4f}\")\n", "print(f\"Std: {mat.std():.4f}\")\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 8: Replace Odd Numbers Without Modifying Original\n", "\n", "**Question:** Given `arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])`, create a new array `out` where all odd numbers are replaced with -1, while leaving `arr` untouched.\n" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Original: [ 1 2 3 4 5 6 7 8 9 10]\n", "Replaced: [-1 2 -1 4 -1 6 -1 8 -1 10]\n" ] } ], "source": [ "arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])\n", "out = np.where(arr % 2 != 0, -1, arr)\n", "print(\"Original:\", arr)\n", "print(\"Replaced:\", out)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 9: Multi-Dimensional Slicing & Shapes\n", "\n", "**Question:** Given `mat = np.arange(36).reshape(6, 6)`, extract:\n", "1. The 4 corner elements as a (2, 2) array.\n", "2. The inner 4x4 matrix (excluding border rows and columns).\n", "3. The 3rd column, but keeping its shape as (6, 1) rather than (6,).\n" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Original 6x6:\n", " [[ 0 1 2 3 4 5]\n", " [ 6 7 8 9 10 11]\n", " [12 13 14 15 16 17]\n", " [18 19 20 21 22 23]\n", " [24 25 26 27 28 29]\n", " [30 31 32 33 34 35]]\n", "\n", "1. Corners (2x2):\n", " [[ 0 5]\n", " [30 35]]\n", "\n", "2. Inner 4x4:\n", " [[ 7 8 9 10]\n", " [13 14 15 16]\n", " [19 20 21 22]\n", " [25 26 27 28]]\n", "\n", "3. Column 2 with kept shape:\n", " [[ 2]\n", " [ 8]\n", " [14]\n", " [20]\n", " [26]\n", " [32]] \n", "Shape: (6, 1)\n" ] } ], "source": [ "mat = np.arange(36).reshape(6, 6)\n", "print(\"Original 6x6:\\n\", mat)\n", "\n", "# 1. Four corners\n", "corners = mat[::5, ::5]\n", "print(\"\\n1. Corners (2x2):\\n\", corners)\n", "\n", "# 2. Inner 4x4\n", "inner = mat[1:-1, 1:-1]\n", "print(\"\\n2. Inner 4x4:\\n\", inner)\n", "\n", "# 3. 3rd column as (6, 1)\n", "col_3 = mat[:, 2:3]\n", "print(\"\\n3. Column 2 with kept shape:\\n\", col_3, \"\\nShape:\", col_3.shape)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 10: Create an 8x8 Checkerboard Pattern\n", "\n", "**Question:** Create an 8x8 matrix filled with 0s and 1s arranged in a checkerboard pattern (where 0 and 1 alternate both horizontally and vertically) using slicing and striding.\n" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "8x8 Checkerboard:\n", " [[0 1 0 1 0 1 0 1]\n", " [1 0 1 0 1 0 1 0]\n", " [0 1 0 1 0 1 0 1]\n", " [1 0 1 0 1 0 1 0]\n", " [0 1 0 1 0 1 0 1]\n", " [1 0 1 0 1 0 1 0]\n", " [0 1 0 1 0 1 0 1]\n", " [1 0 1 0 1 0 1 0]]\n" ] } ], "source": [ "board = np.zeros((8, 8), dtype=int)\n", "board[1::2, ::2] = 1\n", "board[::2, 1::2] = 1\n", "print(\"8x8 Checkerboard:\\n\", board)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 11: Find Common Elements and Matching Positions\n", "\n", "**Question:** Given two arrays:\n", "`a = np.array([1, 2, 3, 2, 3, 4, 3, 4, 5, 6])`\n", "`b = np.array([7, 2, 10, 2, 7, 4, 9, 4, 9, 8])`\n", "1. Find the common unique elements between `a` and `b`.\n", "2. Find the index positions where elements of `a` and `b` match exactly.\n" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Common elements: [2 4]\n", "Matching positions: [1 3 5 7]\n" ] } ], "source": [ "a = np.array([1, 2, 3, 2, 3, 4, 3, 4, 5, 6])\n", "b = np.array([7, 2, 10, 2, 7, 4, 9, 4, 9, 8])\n", "\n", "# 1. Common elements\n", "common = np.intersect1d(a, b)\n", "print(\"Common elements:\", common)\n", "\n", "# 2. Matching positions\n", "matching_idx = np.where(a == b)[0]\n", "print(\"Matching positions:\", matching_idx)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 12: Filter Array with Multiple Conditions\n", "\n", "**Question:** Given `x = np.array([1, 5, 10, 15, 20, 25, 30, 35, 40])`, extract all values that are between 10 and 30 (inclusive) and strictly divisible by 5.\n" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Filtered: [10 15 20 25 30]\n" ] } ], "source": [ "x = np.array([1, 5, 10, 15, 20, 25, 30, 35, 40])\n", "filtered = x[(x >= 10) & (x <= 30) & (x % 5 == 0)]\n", "print(\"Filtered:\", filtered)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 13: Swap Rows in a 2D Matrix\n", "\n", "**Question:** Given `mat = np.arange(16).reshape(4, 4)`, swap row 0 and row 2 in-place or via index reordering.\n" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Before swap:\n", " [[ 0 1 2 3]\n", " [ 4 5 6 7]\n", " [ 8 9 10 11]\n", " [12 13 14 15]]\n", "\n", "After swap:\n", " [[ 8 9 10 11]\n", " [ 4 5 6 7]\n", " [ 0 1 2 3]\n", " [12 13 14 15]]\n" ] } ], "source": [ "mat = np.arange(16).reshape(4, 4)\n", "print(\"Before swap:\\n\", mat)\n", "\n", "# Swapping row 0 and row 2\n", "mat[[0, 2]] = mat[[2, 0]]\n", "print(\"\\nAfter swap:\\n\", mat)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 14: Column-Wise Mean Subtraction (Broadcasting)\n", "\n", "**Question:** Given a 5x3 matrix with random floats, subtract each column's mean from the corresponding column so that each resulting column has a mean of 0. Verify the result.\n" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Original matrix:\n", " [[35.48 20.79 11.64]\n", " [10.66 42.53 46.51]\n", " [34.27 39.18 31.74]\n", " [47.4 42.63 10.11]\n", " [44.3 11.34 39.19]]\n", "\n", "Centered matrix:\n", " [[ 1.06 -10.5 -16.2 ]\n", " [-23.76 11.23 18.67]\n", " [ -0.16 7.88 3.91]\n", " [ 12.98 11.34 -17.73]\n", " [ 9.88 -19.95 11.35]]\n", "New column means (should be ~0): [0. 0. 0.]\n" ] } ], "source": [ "rng = np.random.default_rng(0)\n", "X = rng.uniform(10, 50, size=(5, 3))\n", "print(\"Original matrix:\\n\", np.round(X, 2))\n", "\n", "# Compute column means: shape (3,) broadcasts across 5 rows\n", "col_means = np.mean(X, axis=0)\n", "X_centered = X - col_means\n", "print(\"\\nCentered matrix:\\n\", np.round(X_centered, 2))\n", "print(\"New column means (should be ~0):\", np.round(np.mean(X_centered, axis=0), 5))\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 15: Replace the Maximum Value with Zero\n", "\n", "**Question:** Given a 1D array of 10 random numbers between 0 and 1, find the index of the maximum value using `argmax()` and set that value to 0.\n" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Original: [0.682 0.054 0.22 0.184 0.176 0.812 0.923 0.277 0.82 0.89 ]\n", "Max value 0.923 at index 6\n", "After zeroing max: [0.682 0.054 0.22 0.184 0.176 0.812 0. 0.277 0.82 0.89 ]\n" ] } ], "source": [ "rng = np.random.default_rng(123)\n", "v = rng.random(10)\n", "print(\"Original:\", np.round(v, 3))\n", "\n", "max_idx = np.argmax(v)\n", "print(f\"Max value {v[max_idx]:.3f} at index {max_idx}\")\n", "v[max_idx] = 0.0\n", "print(\"After zeroing max:\", np.round(v, 3))\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 16: Find Mode and Frequency using `np.unique`\n", "\n", "**Question:** Given `arr = np.array([4, 2, 7, 2, 5, 2, 9, 7, 7, 7, 3, 1, 7])`, find the most frequently occurring element (the mode) and its frequency using `np.unique`.\n" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Mode: 7 (occurred 5 times)\n" ] } ], "source": [ "arr = np.array([4, 2, 7, 2, 5, 2, 9, 7, 7, 7, 3, 1, 7])\n", "vals, counts = np.unique(arr, return_counts=True)\n", "mode_idx = np.argmax(counts)\n", "print(f\"Mode: {vals[mode_idx]} (occurred {counts[mode_idx]} times)\")\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 17: Flattening: View vs Copy Demonstration\n", "\n", "**Question:** Create a 3x3 matrix. Obtain a 1D version using `ravel()` and another using `flatten()`. Modify the first element of both. Observe and explain which one altered the original matrix.\n" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Original:\n", " [[1 2 3]\n", " [4 5 6]\n", " [7 8 9]]\n", "\n", "Original after modifying rav[0] and flat[1]:\n", " [[999 2 3]\n", " [ 4 5 6]\n", " [ 7 8 9]]\n", "\n", "Explanation: ravel() returns a VIEW (sharing memory buffer), so orig[0,0] changed to 999. flatten() returns a new COPY, so flat[1] mutation had no effect on orig.\n" ] } ], "source": [ "orig = np.arange(1, 10).reshape(3, 3)\n", "print(\"Original:\\n\", orig)\n", "\n", "rav = orig.ravel()\n", "flat = orig.flatten()\n", "\n", "rav[0] = 999\n", "flat[1] = 888\n", "\n", "print(\"\\nOriginal after modifying rav[0] and flat[1]:\\n\", orig)\n", "print(\"\\nExplanation: ravel() returns a VIEW (sharing memory buffer), so orig[0,0] changed to 999. flatten() returns a new COPY, so flat[1] mutation had no effect on orig.\")\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 18: Stacking Arrays Horizontally, Vertically and Depth-wise\n", "\n", "**Question:** Given `A = np.arange(4).reshape(2, 2)` and `B = np.ones((2, 2))`, produce:\n", "1. Vertical stack `(4, 2)`\n", "2. Horizontal stack `(2, 4)`\n", "3. Depth-wise stack `(2, 2, 2)`\n" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1. Vertical Stack:\n", " [[0. 1.]\n", " [2. 3.]\n", " [1. 1.]\n", " [1. 1.]]\n", "\n", "2. Horizontal Stack:\n", " [[0. 1. 1. 1.]\n", " [2. 3. 1. 1.]]\n", "\n", "3. Depth Stack Shape: (2, 2, 2)\n" ] } ], "source": [ "A = np.arange(4).reshape(2, 2)\n", "B = np.ones((2, 2))\n", "\n", "print(\"1. Vertical Stack:\\n\", np.vstack([A, B]))\n", "print(\"\\n2. Horizontal Stack:\\n\", np.hstack([A, B]))\n", "print(\"\\n3. Depth Stack Shape:\", np.dstack([A, B]).shape)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 19: Cumulative Sum and Product Along Axes\n", "\n", "**Question:** Given `M = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])`, compute:\n", "1. Cumulative sum down columns (axis=0).\n", "2. Cumulative product across rows (axis=1).\n" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1. Cumulative sum down columns (axis=0):\n", " [[ 1 2 3]\n", " [ 5 7 9]\n", " [12 15 18]]\n", "\n", "2. Cumulative product across rows (axis=1):\n", " [[ 1 2 6]\n", " [ 4 20 120]\n", " [ 7 56 504]]\n" ] } ], "source": [ "M = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n", "print(\"1. Cumulative sum down columns (axis=0):\\n\", np.cumsum(M, axis=0))\n", "print(\"\\n2. Cumulative product across rows (axis=1):\\n\", np.cumprod(M, axis=1))\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Problem 20: Vectorized Value Clipping\n", "\n", "**Question:** Given `arr = np.array([-2.5, -0.5, 0.2, 1.8, -1.2, 0.9, 2.3])`, clip all values to the range `[-1.0, 1.0]`:\n", "1. Using boolean masking / indexing.\n", "2. Using `np.clip`.\n", "Verify both yield identical results.\n" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Method 1 (Masking): [-1. -0.5 0.2 1. -1. 0.9 1. ]\n", "Method 2 (np.clip): [-1. -0.5 0.2 1. -1. 0.9 1. ]\n", "Are they identical? True\n" ] } ], "source": [ "arr = np.array([-2.5, -0.5, 0.2, 1.8, -1.2, 0.9, 2.3])\n", "\n", "# Method 1: Boolean masking\n", "c1 = arr.copy()\n", "c1[c1 < -1.0] = -1.0\n", "c1[c1 > 1.0] = 1.0\n", "\n", "# Method 2: np.clip\n", "c2 = np.clip(arr, -1.0, 1.0)\n", "\n", "print(\"Method 1 (Masking):\", c1)\n", "print(\"Method 2 (np.clip):\", c2)\n", "print(\"Are they identical?\", np.array_equal(c1, c2))\n" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.0" } }, "nbformat": 4, "nbformat_minor": 4 }