diff --git a/python-data/exercises/ex06a_numpy.ipynb b/python-data/exercises/ex06a_numpy.ipynb new file mode 100644 index 0000000..4ea97ed --- /dev/null +++ b/python-data/exercises/ex06a_numpy.ipynb @@ -0,0 +1,896 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "de2a613e-7102-4e10-8fee-4d07c0e1f9eb", + "metadata": { + "editable": true, + "slideshow": { + "slide_type": "" + }, + "tags": [] + }, + "source": [ + "# Exercise 6a: numpy" + ] + }, + { + "cell_type": "markdown", + "id": "ea1f5d14-d8ac-4c83-a0fa-54b2309f8cd1", + "metadata": {}, + "source": [ + "## Aim: Get an overview of NumPy and some useful functions." + ] + }, + { + "cell_type": "markdown", + "id": "bd5f0117-b46f-475a-b6da-f4918a40f284", + "metadata": { + "editable": true, + "slideshow": { + "slide_type": "" + }, + "tags": [] + }, + "source": [ + "You can find the teaching resources for this lesson here: https://numpy.org/doc/stable/user/quickstart.html" + ] + }, + { + "cell_type": "markdown", + "id": "8e3500eb-400a-45e4-b108-27a337b2fb84", + "metadata": {}, + "source": [ + "### Issues covered:\n", + "- Importing NumPy\n", + "- Array creation\n", + "- Array indexing and slicing\n", + "- Array operations" + ] + }, + { + "cell_type": "markdown", + "id": "91d90486-6b89-495c-b5bb-fb610dc73e15", + "metadata": { + "editable": true, + "slideshow": { + "slide_type": "" + }, + "tags": [] + }, + "source": [ + "## 1. Basics" + ] + }, + { + "cell_type": "markdown", + "id": "564704e3-b77a-45d3-a3ee-cb00feac6275", + "metadata": {}, + "source": [ + "### Importing NumPy" + ] + }, + { + "cell_type": "markdown", + "id": "cb507a6c-6946-4916-80ba-6996f79b32a4", + "metadata": {}, + "source": [ + "Q1. First, let's use the conventional way to import NumPy into our notebook. You'll need to run this cell to get the rest of the notebook to work!" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "b7b2c772-9185-4fa7-9cf7-61f5b53d56aa", + "metadata": { + "execution": { + "iopub.execute_input": "2024-11-07T16:45:34.152395Z", + "iopub.status.busy": "2024-11-07T16:45:34.151744Z", + "iopub.status.idle": "2024-11-07T16:45:34.605734Z", + "shell.execute_reply": "2024-11-07T16:45:34.604361Z" + } + }, + "outputs": [], + "source": [ + "import numpy as np" + ] + }, + { + "cell_type": "markdown", + "id": "743d7668-3ea1-4d4f-82d6-89ba93d5915f", + "metadata": {}, + "source": [ + "### Array creation" + ] + }, + { + "cell_type": "markdown", + "id": "f78525c3-6a0a-44be-a898-84f5af46a25e", + "metadata": {}, + "source": [ + "Q2. Let's start by creating some arrays - try to create an array using `a = np.array(1, 2, 3, 4)`. Does this work? Can you edit it to make it work?" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "56419349-939c-48df-b696-2f7c08ae7f41", + "metadata": { + "allow_errors": true, + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:45:34.612679Z", + "iopub.status.busy": "2024-11-07T16:45:34.611936Z", + "iopub.status.idle": "2024-11-07T16:45:34.787723Z", + "shell.execute_reply": "2024-11-07T16:45:34.786851Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "allow_errors", + "clear_answer_cell" + ] + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "c7db7e8a-cdf5-4eaa-b1a5-301d89d170c6", + "metadata": { + "editable": true, + "slideshow": { + "slide_type": "" + }, + "tags": [] + }, + "source": [ + "Q3. Take a look at the following numpy array:\n", + "```\n", + "[[7.0, 8.0, 4.0, 2.0],\n", + " [12.0, 1.0, 0.0, 10.0],\n", + " [0.0, 0.0, 0.0, 0.0]]\n", + "```\n", + "- How many axes does it have?\n", + "- What is the length of the array?\n", + "\n", + "Hint: you can use `.ndim` and `.shape` to help if you enclose the array in `np.array()` to define the array." + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "0c33dc0e-fd79-4839-ac13-79ba785e78d3", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:45:34.793395Z", + "iopub.status.busy": "2024-11-07T16:45:34.793168Z", + "iopub.status.idle": "2024-11-07T16:45:34.799661Z", + "shell.execute_reply": "2024-11-07T16:45:34.798857Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "861d15c0-c5fa-4d34-84bf-154980a66088", + "metadata": {}, + "source": [ + "Q4. Can you come up with an example of what a 3D array would look like? Use `np.zeros` to make it then print it out and have a look at `.ndim` and `.shape`" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "1756a861-f70d-4889-9244-a229d9b2e7b7", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:45:34.803567Z", + "iopub.status.busy": "2024-11-07T16:45:34.803346Z", + "iopub.status.idle": "2024-11-07T16:45:34.814135Z", + "shell.execute_reply": "2024-11-07T16:45:34.813304Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "73d932df-887b-455f-93b2-ec265546b6cf", + "metadata": {}, + "source": [ + "Q5.\n", + "- How many elements are in your array? Use `.size` to check.\n", + "- What type are the elements in the array? Use `.dtype` to check.\n", + "- How many bites are in each element of the array? Use `.itemsize` to check." + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "3d3c5463-aa6a-4167-9154-7b7f133e7bc3", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:45:34.818082Z", + "iopub.status.busy": "2024-11-07T16:45:34.817384Z", + "iopub.status.idle": "2024-11-07T16:45:34.830374Z", + "shell.execute_reply": "2024-11-07T16:45:34.829130Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "cb62bfcd-e67a-42ed-9980-1578002f9d3f", + "metadata": {}, + "source": [ + "Q6. Create a 1D array of nine numbers 1-9 using `a = np.linspace(1, 9, 9)`. Reshape this to be a 3x3 array and print it." + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "aacebcbe-ef1a-4813-bc35-a65b061c4f8b", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:45:34.835664Z", + "iopub.status.busy": "2024-11-07T16:45:34.835106Z", + "iopub.status.idle": "2024-11-07T16:45:34.844780Z", + "shell.execute_reply": "2024-11-07T16:45:34.843863Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "2f2f3bfe-4776-46a1-ad0c-8995322aba55", + "metadata": {}, + "source": [ + "### Basic operations" + ] + }, + { + "cell_type": "markdown", + "id": "63700027-be94-4a47-9600-ef5ea449e1b4", + "metadata": {}, + "source": [ + "Q7. What happens if you multiply the previous array by 2 using `b = a*2`?" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "id": "13b608bb-39cb-47cc-a97e-87c33cb4fe2a", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:45:34.848560Z", + "iopub.status.busy": "2024-11-07T16:45:34.848102Z", + "iopub.status.idle": "2024-11-07T16:45:34.861932Z", + "shell.execute_reply": "2024-11-07T16:45:34.860524Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "6ac2f29e-b42c-4e0b-9809-07938ae3aa5e", + "metadata": {}, + "source": [ + "Q8. How do you do matrix multiplication? Try doing the matrix product of `a` and `b`." + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "id": "80b1fc56-e095-435c-b3c6-25afce442071", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:45:34.867769Z", + "iopub.status.busy": "2024-11-07T16:45:34.866526Z", + "iopub.status.idle": "2024-11-07T16:45:34.877181Z", + "shell.execute_reply": "2024-11-07T16:45:34.875920Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "6b76ea97-318a-4bfd-964c-f72d85459f85", + "metadata": {}, + "source": [ + "Q9. When performing operations between arrays of different data types, numpy automatically converts the result to the more precise type - this is called upcasting. Let's demonstrate this concept:\n", + "- Create an array with 3 elements all set to one using `a = np.ones(3, dtype=np.int32)` and set the data type to `np.int32`\n", + "- Create a float array of 3 elements evenly spaced between 0 and π using `b = np.linspace(0, np.pi, 3)`. The data type will be `float64` by default\n", + "- Check the data type of both arrays\n", + "- Add the arrays `a` and `b` to make a new array `c`. Print the resulting array `c` and its data type." + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "id": "8ec1bb60-82f6-4152-9e47-c1d45ab955b0", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:45:34.881234Z", + "iopub.status.busy": "2024-11-07T16:45:34.880863Z", + "iopub.status.idle": "2024-11-07T16:45:34.898208Z", + "shell.execute_reply": "2024-11-07T16:45:34.897270Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "b824fbf3-7184-45fc-8219-a50712941091", + "metadata": {}, + "source": [ + "Q10. For matrix `a` in the previous question, what do you think `a.sum()` would be? Check your answer." + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "id": "91507ae1-8b08-45f1-bd8d-7fbeb5b9dd2c", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:45:34.902680Z", + "iopub.status.busy": "2024-11-07T16:45:34.902077Z", + "iopub.status.idle": "2024-11-07T16:45:34.906767Z", + "shell.execute_reply": "2024-11-07T16:45:34.906211Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "f0fedf38-dff2-43df-8057-4998d7219e31", + "metadata": {}, + "source": [ + "Q11. Create an array using `np.ones(6).reshape(3,2)`. If we only want to sum each column, how would we do that?" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "id": "84d7b08c-5cfe-4662-b7c2-ee9a1fd5cf1d", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:45:34.911338Z", + "iopub.status.busy": "2024-11-07T16:45:34.911068Z", + "iopub.status.idle": "2024-11-07T16:45:34.921502Z", + "shell.execute_reply": "2024-11-07T16:45:34.920616Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "c6d39222-c0a5-4013-83ce-182dfab3ea2e", + "metadata": {}, + "source": [ + "### Indexing" + ] + }, + { + "cell_type": "markdown", + "id": "7b2b1a58-8c3e-480f-950a-ccf3a813b8cd", + "metadata": { + "editable": true, + "slideshow": { + "slide_type": "" + }, + "tags": [] + }, + "source": [ + "Q12.\n", + "- Create a 1D array of size 20 where each element is the cube of its index.\n", + "- Print the 5th element of `a`. Hint: your answer should be 64 - remember where we start indexing." + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "id": "f50807ff-0025-4e89-8a17-1ea2988cc367", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:45:34.925203Z", + "iopub.status.busy": "2024-11-07T16:45:34.924904Z", + "iopub.status.idle": "2024-11-07T16:45:34.938051Z", + "shell.execute_reply": "2024-11-07T16:45:34.937079Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "8793e6ef-144a-440f-aa9e-5b49dc4a583d", + "metadata": {}, + "source": [ + "Q13. Slice the array to get elements from index 3 to index 7 (inclusive)." + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "id": "7c45834d-1a39-4037-9bf1-ca97c8dab09d", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:45:34.942117Z", + "iopub.status.busy": "2024-11-07T16:45:34.941465Z", + "iopub.status.idle": "2024-11-07T16:45:34.955086Z", + "shell.execute_reply": "2024-11-07T16:45:34.953727Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "3be02020-6449-4a8c-a1f6-bf6fafb6ec12", + "metadata": {}, + "source": [ + "Q14. Change every 3rd element to -1. This should give: `[ -1, 1, 8, -1, 64, 125, -1, ... ]`" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "id": "f16bfe38-1f6f-47fd-a7f2-2a9da0333a8b", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:45:34.961165Z", + "iopub.status.busy": "2024-11-07T16:45:34.960785Z", + "iopub.status.idle": "2024-11-07T16:45:34.971049Z", + "shell.execute_reply": "2024-11-07T16:45:34.970204Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "eb80452e-cd4f-4971-825d-86cb4747d9da", + "metadata": {}, + "source": [ + "Q15. Reverse the array and print the result." + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "id": "169e63ce-9d74-4a35-b386-d2bd07bad3a7", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:45:34.976296Z", + "iopub.status.busy": "2024-11-07T16:45:34.975378Z", + "iopub.status.idle": "2024-11-07T16:45:34.987276Z", + "shell.execute_reply": "2024-11-07T16:45:34.986061Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "1cd5271c-8a90-49ae-979b-d89575491b01", + "metadata": {}, + "source": [ + "Q16. Create a 3x4 numpy array `b` using `b = np.array([[2 * i + j for j in range(4)] for i in range(3)])`." + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "id": "5536dff6-d6c2-4dab-a4e6-869629e0edeb", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:45:34.991370Z", + "iopub.status.busy": "2024-11-07T16:45:34.990844Z", + "iopub.status.idle": "2024-11-07T16:45:35.005952Z", + "shell.execute_reply": "2024-11-07T16:45:35.003808Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "3983a14f-de1d-490b-b6fd-4f4d7eda14fb", + "metadata": {}, + "source": [ + "Q17. Print the element in the second row and third column. This should be 4." + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "id": "a734ee36-b794-4260-808c-575518b4a34e", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:45:35.010659Z", + "iopub.status.busy": "2024-11-07T16:45:35.009978Z", + "iopub.status.idle": "2024-11-07T16:45:35.021059Z", + "shell.execute_reply": "2024-11-07T16:45:35.020149Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "3e4d5ba7-1abe-4285-bd7b-29bca9febbf1", + "metadata": {}, + "source": [ + "Q18. Extract and print the second column as a 1D array." + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "id": "e190b233-124d-40c3-b928-c66f015217df", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:45:35.024197Z", + "iopub.status.busy": "2024-11-07T16:45:35.023920Z", + "iopub.status.idle": "2024-11-07T16:45:35.035750Z", + "shell.execute_reply": "2024-11-07T16:45:35.034822Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "24b839b8-a010-4bd5-afdc-f7046c7acc26", + "metadata": {}, + "source": [ + "Q19. Extract and print a sub-array containing the last two rows." + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "id": "6efa59b9-0bc1-4a8b-ae32-4ffbe75512cb", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:45:35.038908Z", + "iopub.status.busy": "2024-11-07T16:45:35.038379Z", + "iopub.status.idle": "2024-11-07T16:45:35.051161Z", + "shell.execute_reply": "2024-11-07T16:45:35.050287Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "d4fb0210-2031-4435-bdae-b567a6010c42", + "metadata": {}, + "source": [ + "Q20. Use slicing to replace the last row with the values `[7, 7, 7, 7]`." + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "id": "d2e59188-020a-4c03-a373-9d50b0def22f", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:45:35.054713Z", + "iopub.status.busy": "2024-11-07T16:45:35.054443Z", + "iopub.status.idle": "2024-11-07T16:45:35.068244Z", + "shell.execute_reply": "2024-11-07T16:45:35.067085Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "161545bc-06dd-40cb-b598-36de4f5378e3", + "metadata": {}, + "source": [ + "Q21. Iterate over the elements of the array using the `.flat` attribute and print them." + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "id": "78081cb7-6c73-466b-a736-1aca4c652f49", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:45:35.074455Z", + "iopub.status.busy": "2024-11-07T16:45:35.073677Z", + "iopub.status.idle": "2024-11-07T16:45:35.082625Z", + "shell.execute_reply": "2024-11-07T16:45:35.081523Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "0ea93892-c626-4e4e-b91c-763daf6bb7e1", + "metadata": {}, + "source": [ + "Q22. Create a 3D array `c` using `c = np.array([[[i * 10 + j * 5 + k for k in range(4)] for j in range(3)] for i in range(2)])`" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "id": "15632b1d-f44e-4a1e-9efb-e6fde75e266b", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:45:35.087438Z", + "iopub.status.busy": "2024-11-07T16:45:35.086993Z", + "iopub.status.idle": "2024-11-07T16:45:35.099686Z", + "shell.execute_reply": "2024-11-07T16:45:35.098567Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "d48d62f7-5ccc-4dc6-a441-cac5ebc4cb10", + "metadata": {}, + "source": [ + "Q23. Print all elements of the first layer of the array." + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "id": "53d8f855-bba0-40a4-aeba-2b719b87b363", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:45:35.103756Z", + "iopub.status.busy": "2024-11-07T16:45:35.103053Z", + "iopub.status.idle": "2024-11-07T16:45:35.118641Z", + "shell.execute_reply": "2024-11-07T16:45:35.117258Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "96fcfb26-8c72-476b-b030-9e1f61a143ab", + "metadata": {}, + "source": [ + "Q24. Use `...` to print the last element of each 1D array contained within c." + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "id": "59fcba5b-3772-4326-9f82-da576e8e6f5d", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:45:35.124400Z", + "iopub.status.busy": "2024-11-07T16:45:35.123593Z", + "iopub.status.idle": "2024-11-07T16:45:35.132851Z", + "shell.execute_reply": "2024-11-07T16:45:35.131940Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "c96b71dd-bb47-41aa-9403-cc51f660aa0d", + "metadata": {}, + "source": [ + "Q25. Modify the first column of the second layer to `[0, 0, 0]`." + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "id": "495e40c1-5584-4e58-9db3-70b380b1fae5", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:45:35.137623Z", + "iopub.status.busy": "2024-11-07T16:45:35.137006Z", + "iopub.status.idle": "2024-11-07T16:45:35.148197Z", + "shell.execute_reply": "2024-11-07T16:45:35.147116Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 + Jaspy", + "language": "python", + "name": "jaspy" + }, + "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.9" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/python-data/exercises/ex06b_numpy.ipynb b/python-data/exercises/ex06b_numpy.ipynb new file mode 100644 index 0000000..9746565 --- /dev/null +++ b/python-data/exercises/ex06b_numpy.ipynb @@ -0,0 +1,559 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "93699150-662a-4a21-bc2b-7836c39d0e0d", + "metadata": { + "editable": true, + "slideshow": { + "slide_type": "" + }, + "tags": [] + }, + "source": [ + "# Exercise 6b: numpy (continued)" + ] + }, + { + "cell_type": "markdown", + "id": "0465143d-b368-4fcb-baec-017e5aaf801b", + "metadata": {}, + "source": [ + "## Aim: Get an overview of NumPy and some useful functions." + ] + }, + { + "cell_type": "markdown", + "id": "0364bf4f-20d1-49bc-8e2e-90f636e579ea", + "metadata": {}, + "source": [ + "You can find the teaching resources for this lesson here: https://numpy.org/doc/stable/user/quickstart.html" + ] + }, + { + "cell_type": "markdown", + "id": "b169c5eb-8467-4830-ba53-8707ad9642d0", + "metadata": {}, + "source": [ + "### Issues covered:\n", + "- Shape manipulation: changing shape, stacking, splitting\n", + "- Copies and views" + ] + }, + { + "cell_type": "markdown", + "id": "bd16b618-3891-4613-9257-a3fbaba8f53f", + "metadata": {}, + "source": [ + "## 2. Shape manipulation" + ] + }, + { + "cell_type": "markdown", + "id": "776d6a74-7fd7-4a76-9388-694a241fcfdf", + "metadata": {}, + "source": [ + "### Changing the shape" + ] + }, + { + "cell_type": "markdown", + "id": "34b119db-ac4b-44cb-96a8-ca00e89cb2db", + "metadata": {}, + "source": [ + "Q1. Use the following to create a 3x4 array: \n", + "```\n", + "rg = np.random.default_rng(1)\n", + "a = np.floor(10 * rg.random((3, 4)))\n", + "```\n", + "Then use the `ravel` method to flatten the array and print it." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "addaf639-10ae-402b-a6e8-6dbbdab747f7", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:44:43.926389Z", + "iopub.status.busy": "2024-11-07T16:44:43.925221Z", + "iopub.status.idle": "2024-11-07T16:44:44.456971Z", + "shell.execute_reply": "2024-11-07T16:44:44.455705Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "4d060d03-973b-4916-80d9-29382400419f", + "metadata": {}, + "source": [ + "Q2. Reshape the array so it has the shape (2,6) and print it." + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "ddd29757-7974-4a25-a3ad-34fbe2910a62", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:44:44.460969Z", + "iopub.status.busy": "2024-11-07T16:44:44.460546Z", + "iopub.status.idle": "2024-11-07T16:44:44.467996Z", + "shell.execute_reply": "2024-11-07T16:44:44.467190Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "78cd0758-225c-4b58-8e84-1e4e3872293f", + "metadata": {}, + "source": [ + "Q3. Transpose the array and print it." + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "ff5c18e1-ea8a-4d78-8b6c-38ac268fe6dc", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:44:44.470550Z", + "iopub.status.busy": "2024-11-07T16:44:44.470296Z", + "iopub.status.idle": "2024-11-07T16:44:44.489171Z", + "shell.execute_reply": "2024-11-07T16:44:44.487883Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "bf99d355-263c-4448-9160-cb433c6297fd", + "metadata": {}, + "source": [ + "Q4. Use the resize method to change the shape of the array to (6,2). Notice the difference between reshape and resize." + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "65805c3d-bfef-4cd2-9a20-d123078f9672", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:44:44.494484Z", + "iopub.status.busy": "2024-11-07T16:44:44.494103Z", + "iopub.status.idle": "2024-11-07T16:44:44.508456Z", + "shell.execute_reply": "2024-11-07T16:44:44.507225Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "0254d87c-8cf2-42e9-9193-fb0a57b99f71", + "metadata": {}, + "source": [ + "Q5. Reshape the array to a shape of (3, -1) and print the reshaped array. Note what `-1` does here." + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "ecd467a6-738c-4b3a-b37a-5f7ded7bb544", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:44:44.514020Z", + "iopub.status.busy": "2024-11-07T16:44:44.513435Z", + "iopub.status.idle": "2024-11-07T16:44:44.532472Z", + "shell.execute_reply": "2024-11-07T16:44:44.530794Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "e24b0985-7938-4d08-aa8a-ffe5b6741823", + "metadata": {}, + "source": [ + "### Stacking" + ] + }, + { + "cell_type": "markdown", + "id": "9150a86b-b60c-4235-99f1-df8a72ea383d", + "metadata": {}, + "source": [ + "Q6.\n", + "- Write a function `stack_arrays` that takes two 2D arrays `a` and `b`, an axis argument and returns the arrays stacked along the specified axis. The function should handle the following cases:\n", + " - Vertical stacking (`axis=0`): Stack the arrays along rows\n", + " - Horizontal stacking (`axis=1`): Stack the arrays along columns\n", + " - Column stacking (`axis=column`): Stack 1D arrays as columns of a 2D array if both a and b are 1D, if they are 2D stack them horizontally\n", + " - If `axis` is set to any other value raise a `ValueError`\n", + "- Once you're happy with your function, try the test cases in the solutions to check your working!" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "21527484-619e-47c0-a222-092ee88fb478", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:44:44.538232Z", + "iopub.status.busy": "2024-11-07T16:44:44.537362Z", + "iopub.status.idle": "2024-11-07T16:44:44.559570Z", + "shell.execute_reply": "2024-11-07T16:44:44.558050Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [] + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Vertical stacking:\n", + " [[9. 7.]\n", + " [5. 2.]\n", + " [1. 9.]\n", + " [5. 1.]]\n", + "\n", + "Horizontal stacking:\n", + " [[9. 7. 1. 9.]\n", + " [5. 2. 5. 1.]]\n", + "\n", + "Column stacking (1D arrays):\n", + " [[4. 3.]\n", + " [2. 8.]]\n" + ] + } + ], + "source": [ + "import numpy as np\n", + "\n", + "def stack_arrays(a, b, axis):\n", + " if axis == 0:\n", + " return np.vstack((a, b))\n", + " elif axis == 1:\n", + " return np.hstack((a,b))\n", + " elif axis == 'column':\n", + " return np.column_stack((a,b))\n", + " else:\n", + " raise ValueError(\"Invalid axis specified. Use 0, 1 or 'column'.\")\n", + "\n", + "# Test cases\n", + "a = np.array([[9,7], [5,2]])\n", + "b = np.array([[1., 9.], [5., 1.]])\n", + "c = np.array([4., 2.])\n", + "d = np.array([3., 8.])\n", + "\n", + "# Vertical stacking\n", + "print(\"Vertical stacking:\\n\", stack_arrays(a, b, axis=0))\n", + "\n", + "# Horizontal stacking\n", + "print(\"\\nHorizontal stacking:\\n\", stack_arrays(a, b, axis=1))\n", + "\n", + "# Column stacking for 1D arrays\n", + "print(\"\\nColumn stacking (1D arrays):\\n\", stack_arrays(c, d, axis='column'))" + ] + }, + { + "cell_type": "markdown", + "id": "54b6c868-dfc8-4113-bf8c-4ec92b72d6c4", + "metadata": {}, + "source": [ + "### Splitting" + ] + }, + { + "cell_type": "markdown", + "id": "9150e1f6-639b-4bce-9777-c35e96e49de8", + "metadata": {}, + "source": [ + "Q7.\n", + "Given the following 2D array `b`:\n", + "```\n", + "rg = np.random.default_rng(42)\n", + "b = np.floor(10 * rg.random((2, 10)))\n", + "```\n", + "- Split the array equally using `np.hsplit` into 5 parts along the horizontal axis. Assign the resulting sub-arrays to a variable named `equal_splits`\n", + "- Split the array after the second and fifth columns using `np.hsplit`. Assign the resulting sub-arrays to a variable called `column_splits`." + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "id": "c7d0c083-8f9d-4431-a68e-a57ee23fa4ff", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:44:44.565408Z", + "iopub.status.busy": "2024-11-07T16:44:44.564948Z", + "iopub.status.idle": "2024-11-07T16:44:44.582739Z", + "shell.execute_reply": "2024-11-07T16:44:44.581210Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "f5c2d6e1-e758-459c-bd22-192651a96507", + "metadata": {}, + "source": [ + "## 3. Copies and views" + ] + }, + { + "cell_type": "markdown", + "id": "dff98f88-d2e0-4b90-ba24-9752ffe36888", + "metadata": {}, + "source": [ + "Q8. Let's demonstrate No Copy:\n", + "- Write a function `test_no_copy()` that:\n", + " - Creates a `3x3` Numpy array `a`.\n", + " - Assigns `b=a` and checks if modifying `b` affects `a`.\n", + " - Returns `True` if `b` is a reference to `a` i.e. no copy is made, and `False` otherwise\n", + " - Hint: use `is` to verify if `a` and `b` are the same object." + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "id": "509b0f88-170f-49de-9e25-672bde58738e", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:44:44.588398Z", + "iopub.status.busy": "2024-11-07T16:44:44.587869Z", + "iopub.status.idle": "2024-11-07T16:44:44.603287Z", + "shell.execute_reply": "2024-11-07T16:44:44.602046Z" + }, + "scrolled": true, + "slideshow": { + "slide_type": "" + }, + "tags": [] + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Testing no copy behavior: True\n" + ] + } + ], + "source": [ + "def test_no_copy():\n", + " a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n", + " b = a\n", + " b[0, 0] = 999\n", + " return b is a # Check if 'b' is a reference to 'a'\n", + "\n", + "print(\"Testing no copy behavior:\", test_no_copy()) # Expected: True" + ] + }, + { + "cell_type": "markdown", + "id": "c1094086-cb82-4541-b9a1-811773050bf8", + "metadata": {}, + "source": [ + "Q9. Let's demonstrate Shallow Copy:\n", + "- Write a function `test_shallow_copy()` that:\n", + " - Creates a `3x3` Numpy array `a`.\n", + " - Creates a shallow copy of `a` using `a.view()` and assigns it to `c`.\n", + " - Modifies an element in `c` and checks if the change is reflected in `a`\n", + " - Verifies that `a` and `c` are not the same object but share data\n", + " - Returns `True` if the modification in `c` also modifies `a` and `False` otherwise\n", + " - Hint: Use `is` to confirm `a` and `c` are different objects, and `c.base is a` to confirm shared data. " + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "id": "4788a3fb-9483-4417-9e6d-52a5cc15de64", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:44:44.609160Z", + "iopub.status.busy": "2024-11-07T16:44:44.608733Z", + "iopub.status.idle": "2024-11-07T16:44:44.631397Z", + "shell.execute_reply": "2024-11-07T16:44:44.629854Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "fd0dc68d-9a11-4f86-a4c9-c1e8fd10946c", + "metadata": {}, + "source": [ + "Q10. Let's demonstrate Deep Copy: \n", + "- Write a function `test_deep_copy()`that:\n", + " - Creates a `3x3` Numpy array `a`\n", + " - Creates a deep copy of `a` using `a.copy()` and assigns it to `d`\n", + " - Modifies an element in `d` and checks if the change is reflected in `a`\n", + " - Verifies that `a` and `d` do not share data\n", + " - Returns `True` if `a` and `d` do not share data and `False` if they do. " + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "id": "899f1587-f732-487a-a06c-b4f58d9d9af7", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:44:44.637952Z", + "iopub.status.busy": "2024-11-07T16:44:44.637302Z", + "iopub.status.idle": "2024-11-07T16:44:44.657136Z", + "shell.execute_reply": "2024-11-07T16:44:44.655518Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [] + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Testing deep copy behavior: True\n" + ] + } + ], + "source": [ + "def test_deep_copy():\n", + " a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n", + " d = a.copy()\n", + " d[0, 0] = 999\n", + " return d.base is None and np.any(a != d) # Check if 'd' is a true deep copy\n", + "\n", + "print(\"Testing deep copy behavior:\", test_deep_copy()) # Expected: True" + ] + }, + { + "cell_type": "markdown", + "id": "d2493f55-f912-44bf-8ea2-90bb588d490a", + "metadata": { + "editable": true, + "slideshow": { + "slide_type": "" + }, + "tags": [] + }, + "source": [ + "Q11. Let's demonstrate Memory Management: \n", + "- Write a function `memory_management_example()` that:\n", + " - Creates a large array `a` of 10 million elements\n", + " - Creates a slice of `a` containing the first 10 elements and assigns it to `b`\n", + " - Deletes `a` and observes what happens to `b`\n", + " - Creates another slice of `a` containing the first 1- elements but it copies it deeply this time assigning it to `c`\n", + " - Deletes `a` and observes if `c` is still accessible\n", + " - Returns `True` if `b` cannot be accessed after deleting `a`, but `c` can and `False` otherwise\n", + " - Hint: use a try-except block to handle errors from accessing `b` after deleting `a`" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "id": "91110ee3-d12d-41ba-8394-82b32f5f2e6f", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:44:44.663498Z", + "iopub.status.busy": "2024-11-07T16:44:44.662919Z", + "iopub.status.idle": "2024-11-07T16:44:44.725925Z", + "shell.execute_reply": "2024-11-07T16:44:44.724218Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 + Jaspy", + "language": "python", + "name": "jaspy" + }, + "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.9" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/python-data/solutions/ex06_numpy.ipynb b/python-data/solutions/ex06_numpy.ipynb deleted file mode 100644 index 034d6ab..0000000 --- a/python-data/solutions/ex06_numpy.ipynb +++ /dev/null @@ -1,97 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "de2a613e-7102-4e10-8fee-4d07c0e1f9eb", - "metadata": {}, - "source": [ - "# Exercise 6: numpy" - ] - }, - { - "cell_type": "markdown", - "id": "91d90486-6b89-495c-b5bb-fb610dc73e15", - "metadata": {}, - "source": [ - "## Basics" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "58ccfac7-b803-4d9d-a728-c3dc08ca8db5", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "79f773e8-ab4e-4273-b398-b1a6f5682677", - "metadata": {}, - "source": [ - "## Shape manipulation" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "8b7141e5-f59f-47bd-a26c-19d342df5d18", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "288fc0f9-7014-4d9b-9b02-475b9c99d4e7", - "metadata": {}, - "source": [ - "## Copies and views" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "182c4af3-c08d-40f2-a08b-4b3fe427b155", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "5e6e8f7e-6d3b-4405-bc1c-4afa9d6188d4", - "metadata": {}, - "source": [ - "## Advanced" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "dc6e841f-074d-4d8d-9f6e-63e4f2032ff1", - "metadata": {}, - "outputs": [], - "source": [] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3 + Jaspy", - "language": "python", - "name": "jaspy" - }, - "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.9" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/python-data/solutions/ex06a_numpy.ipynb b/python-data/solutions/ex06a_numpy.ipynb new file mode 100644 index 0000000..8d7fdc7 --- /dev/null +++ b/python-data/solutions/ex06a_numpy.ipynb @@ -0,0 +1,1290 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "de2a613e-7102-4e10-8fee-4d07c0e1f9eb", + "metadata": { + "editable": true, + "slideshow": { + "slide_type": "" + }, + "tags": [] + }, + "source": [ + "# Exercise 6a: numpy" + ] + }, + { + "cell_type": "markdown", + "id": "ea1f5d14-d8ac-4c83-a0fa-54b2309f8cd1", + "metadata": {}, + "source": [ + "## Aim: Get an overview of NumPy and some useful functions." + ] + }, + { + "cell_type": "markdown", + "id": "bd5f0117-b46f-475a-b6da-f4918a40f284", + "metadata": { + "editable": true, + "slideshow": { + "slide_type": "" + }, + "tags": [] + }, + "source": [ + "You can find the teaching resources for this lesson here: https://numpy.org/doc/stable/user/quickstart.html" + ] + }, + { + "cell_type": "markdown", + "id": "8e3500eb-400a-45e4-b108-27a337b2fb84", + "metadata": {}, + "source": [ + "### Issues covered:\n", + "- Importing NumPy\n", + "- Array creation\n", + "- Array indexing and slicing\n", + "- Array operations" + ] + }, + { + "cell_type": "markdown", + "id": "91d90486-6b89-495c-b5bb-fb610dc73e15", + "metadata": { + "editable": true, + "slideshow": { + "slide_type": "" + }, + "tags": [] + }, + "source": [ + "## 1. Basics" + ] + }, + { + "cell_type": "markdown", + "id": "564704e3-b77a-45d3-a3ee-cb00feac6275", + "metadata": {}, + "source": [ + "### Importing NumPy" + ] + }, + { + "cell_type": "markdown", + "id": "cb507a6c-6946-4916-80ba-6996f79b32a4", + "metadata": {}, + "source": [ + "Q1. First, let's use the conventional way to import NumPy into our notebook. You'll need to run this cell to get the rest of the notebook to work!" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "b7b2c772-9185-4fa7-9cf7-61f5b53d56aa", + "metadata": { + "execution": { + "iopub.execute_input": "2024-11-07T16:45:34.152395Z", + "iopub.status.busy": "2024-11-07T16:45:34.151744Z", + "iopub.status.idle": "2024-11-07T16:45:34.605734Z", + "shell.execute_reply": "2024-11-07T16:45:34.604361Z" + } + }, + "outputs": [], + "source": [ + "import numpy as np" + ] + }, + { + "cell_type": "markdown", + "id": "743d7668-3ea1-4d4f-82d6-89ba93d5915f", + "metadata": {}, + "source": [ + "### Array creation" + ] + }, + { + "cell_type": "markdown", + "id": "f78525c3-6a0a-44be-a898-84f5af46a25e", + "metadata": {}, + "source": [ + "Q2. Let's start by creating some arrays - try to create an array using `a = np.array(1, 2, 3, 4)`. Does this work? Can you edit it to make it work?" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "56419349-939c-48df-b696-2f7c08ae7f41", + "metadata": { + "allow_errors": true, + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:45:34.612679Z", + "iopub.status.busy": "2024-11-07T16:45:34.611936Z", + "iopub.status.idle": "2024-11-07T16:45:34.787723Z", + "shell.execute_reply": "2024-11-07T16:45:34.786851Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "allow_errors", + "clear_answer_cell" + ] + }, + "outputs": [ + { + "ename": "TypeError", + "evalue": "array() takes from 1 to 2 positional arguments but 4 were given", + "output_type": "error", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", + "Cell \u001b[0;32mIn[2], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m a \u001b[38;5;241m=\u001b[39m \u001b[43mnp\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43marray\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;241;43m1\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m2\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m3\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m4\u001b[39;49m\u001b[43m)\u001b[49m\n\u001b[1;32m 2\u001b[0m \u001b[38;5;66;03m# You need to use the square brackets:\u001b[39;00m\n\u001b[1;32m 3\u001b[0m a \u001b[38;5;241m=\u001b[39m np\u001b[38;5;241m.\u001b[39marray([\u001b[38;5;241m1\u001b[39m, \u001b[38;5;241m2\u001b[39m, \u001b[38;5;241m3\u001b[39m, \u001b[38;5;241m4\u001b[39m])\n", + "\u001b[0;31mTypeError\u001b[0m: array() takes from 1 to 2 positional arguments but 4 were given" + ] + } + ], + "source": [ + "a = np.array(1, 2, 3, 4)\n", + "# You need to use the square brackets:\n", + "a = np.array([1, 2, 3, 4])" + ] + }, + { + "cell_type": "markdown", + "id": "c7db7e8a-cdf5-4eaa-b1a5-301d89d170c6", + "metadata": { + "editable": true, + "slideshow": { + "slide_type": "" + }, + "tags": [] + }, + "source": [ + "Q3. Take a look at the following numpy array:\n", + "```\n", + "[[7.0, 8.0, 4.0, 2.0],\n", + " [12.0, 1.0, 0.0, 10.0],\n", + " [0.0, 0.0, 0.0, 0.0]]\n", + "```\n", + "- How many axes does it have?\n", + "- What is the length of the array?\n", + "\n", + "Hint: you can use `.ndim` and `.shape` to help if you enclose the array in `np.array()` to define the array." + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "0c33dc0e-fd79-4839-ac13-79ba785e78d3", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:45:34.793395Z", + "iopub.status.busy": "2024-11-07T16:45:34.793168Z", + "iopub.status.idle": "2024-11-07T16:45:34.799661Z", + "shell.execute_reply": "2024-11-07T16:45:34.798857Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Number of axes/dimensions: 2\n", + "Length of array: (3, 4)\n" + ] + } + ], + "source": [ + "array = np.array([[7.0, 8.0, 4.0, 2.0], [12.0, 1.0, 0.0, 10.0], [0.0, 0.0, 0.0, 0.0]])\n", + "print(\"Number of axes/dimensions:\", array.ndim)\n", + "# There are 2 dimensions! It's a 2D array because it has rows and columns. Even though there are three sets of [ ] brackets, the structure is still 2D because each row is a 1D array and multiple rows together form the 2D array. \n", + "print(\"Length of array:\", array.shape)\n", + "# The first dimension (rows) is the outermost brackets - in our case it is 3. The second dimension (columns) is the number of values in each of the inner brackets, which is 4 in our case." + ] + }, + { + "cell_type": "markdown", + "id": "861d15c0-c5fa-4d34-84bf-154980a66088", + "metadata": {}, + "source": [ + "Q4. Can you come up with an example of what a 3D array would look like? Use `np.zeros` to make it then print it out and have a look at `.ndim` and `.shape`" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "1756a861-f70d-4889-9244-a229d9b2e7b7", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:45:34.803567Z", + "iopub.status.busy": "2024-11-07T16:45:34.803346Z", + "iopub.status.idle": "2024-11-07T16:45:34.814135Z", + "shell.execute_reply": "2024-11-07T16:45:34.813304Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[[0. 0.]\n", + " [0. 0.]\n", + " [0. 0.]\n", + " [0. 0.]]\n", + "\n", + " [[0. 0.]\n", + " [0. 0.]\n", + " [0. 0.]\n", + " [0. 0.]]\n", + "\n", + " [[0. 0.]\n", + " [0. 0.]\n", + " [0. 0.]\n", + " [0. 0.]]]\n", + "Number of dimensions: 3\n", + "Length of array: (3, 4, 2)\n" + ] + } + ], + "source": [ + "array_3d = np.zeros((3,4,2))\n", + "print(array_3d)\n", + "print(\"Number of dimensions:\", array_3d.ndim)\n", + "print(\"Length of array:\", array_3d.shape)\n", + "# A 3D array in numpy can be thought of as a collection of 2D arrays stacked together. Each layer is a 2D array and the third dimension is how many 2D arrays are stacked - in this case we have three lots of 2D arrays with 4 rows and 2 columns" + ] + }, + { + "cell_type": "markdown", + "id": "73d932df-887b-455f-93b2-ec265546b6cf", + "metadata": {}, + "source": [ + "Q5.\n", + "- How many elements are in your array? Use `.size` to check.\n", + "- What type are the elements in the array? Use `.dtype` to check.\n", + "- How many bites are in each element of the array? Use `.itemsize` to check." + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "3d3c5463-aa6a-4167-9154-7b7f133e7bc3", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:45:34.818082Z", + "iopub.status.busy": "2024-11-07T16:45:34.817384Z", + "iopub.status.idle": "2024-11-07T16:45:34.830374Z", + "shell.execute_reply": "2024-11-07T16:45:34.829130Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Number of elements: 24\n", + "Type of elements: float64\n", + "Bytes per element: 8\n" + ] + } + ], + "source": [ + "print(\"Number of elements:\", array_3d.size)\n", + "print(\"Type of elements:\", array_3d.dtype)\n", + "print(\"Bytes per element:\", array_3d.itemsize)" + ] + }, + { + "cell_type": "markdown", + "id": "cb62bfcd-e67a-42ed-9980-1578002f9d3f", + "metadata": {}, + "source": [ + "Q6. Create a 1D array of nine numbers 1-9 using `a = np.linspace(1, 9, 9)`. Reshape this to be a 3x3 array and print it." + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "aacebcbe-ef1a-4813-bc35-a65b061c4f8b", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:45:34.835664Z", + "iopub.status.busy": "2024-11-07T16:45:34.835106Z", + "iopub.status.idle": "2024-11-07T16:45:34.844780Z", + "shell.execute_reply": "2024-11-07T16:45:34.843863Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[1. 2. 3.]\n", + " [4. 5. 6.]\n", + " [7. 8. 9.]]\n" + ] + } + ], + "source": [ + "a = np.linspace(1, 9, 9).reshape(3,3)\n", + "print(a)" + ] + }, + { + "cell_type": "markdown", + "id": "2f2f3bfe-4776-46a1-ad0c-8995322aba55", + "metadata": {}, + "source": [ + "### Basic operations" + ] + }, + { + "cell_type": "markdown", + "id": "63700027-be94-4a47-9600-ef5ea449e1b4", + "metadata": {}, + "source": [ + "Q7. What happens if you multiply the previous array by 2 using `b = a*2`?" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "id": "13b608bb-39cb-47cc-a97e-87c33cb4fe2a", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:45:34.848560Z", + "iopub.status.busy": "2024-11-07T16:45:34.848102Z", + "iopub.status.idle": "2024-11-07T16:45:34.861932Z", + "shell.execute_reply": "2024-11-07T16:45:34.860524Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[ 2. 4. 6.]\n", + " [ 8. 10. 12.]\n", + " [14. 16. 18.]]\n" + ] + } + ], + "source": [ + "b = a*2\n", + "# The array has been multiplied by two elementwise (not matrix multiplication)\n", + "print(b)" + ] + }, + { + "cell_type": "markdown", + "id": "6ac2f29e-b42c-4e0b-9809-07938ae3aa5e", + "metadata": {}, + "source": [ + "Q8. How do you do matrix multiplication? Try doing the matrix product of `a` and `b`." + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "id": "80b1fc56-e095-435c-b3c6-25afce442071", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:45:34.867769Z", + "iopub.status.busy": "2024-11-07T16:45:34.866526Z", + "iopub.status.idle": "2024-11-07T16:45:34.877181Z", + "shell.execute_reply": "2024-11-07T16:45:34.875920Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[ 60. 72. 84.]\n", + " [132. 162. 192.]\n", + " [204. 252. 300.]]\n" + ] + } + ], + "source": [ + "# Either of these methods work\n", + "matrix_product = a @ b\n", + "matrix_product = a.dot(b)\n", + "print(matrix_product)" + ] + }, + { + "cell_type": "markdown", + "id": "6b76ea97-318a-4bfd-964c-f72d85459f85", + "metadata": {}, + "source": [ + "Q9. When performing operations between arrays of different data types, numpy automatically converts the result to the more precise type - this is called upcasting. Let's demonstrate this concept:\n", + "- Create an array with 3 elements all set to one using `a = np.ones(3, dtype=np.int32)` and set the data type to `np.int32`\n", + "- Create a float array of 3 elements evenly spaced between 0 and π using `b = np.linspace(0, np.pi, 3)`. The data type will be `float64` by default\n", + "- Check the data type of both arrays\n", + "- Add the arrays `a` and `b` to make a new array `c`. Print the resulting array `c` and its data type." + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "id": "8ec1bb60-82f6-4152-9e47-c1d45ab955b0", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:45:34.881234Z", + "iopub.status.busy": "2024-11-07T16:45:34.880863Z", + "iopub.status.idle": "2024-11-07T16:45:34.898208Z", + "shell.execute_reply": "2024-11-07T16:45:34.897270Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Data type of a: int32\n", + "Data type of b: float64\n", + "Data type of c: float64\n" + ] + }, + { + "data": { + "text/plain": [ + "array([1. , 2.57079633, 4.14159265])" + ] + }, + "execution_count": 9, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a = np.ones(3, dtype=np.int32)\n", + "b = np.linspace(0, np.pi, 3)\n", + "c = a + b \n", + "print(\"Data type of a:\", a.dtype) #int32\n", + "print(\"Data type of b:\", b.dtype) #float64\n", + "print(\"Data type of c:\", c.dtype) #float64\n", + "c" + ] + }, + { + "cell_type": "markdown", + "id": "b824fbf3-7184-45fc-8219-a50712941091", + "metadata": {}, + "source": [ + "Q10. For matrix `a` in the previous question, what do you think `a.sum()` would be? Check your answer." + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "id": "91507ae1-8b08-45f1-bd8d-7fbeb5b9dd2c", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:45:34.902680Z", + "iopub.status.busy": "2024-11-07T16:45:34.902077Z", + "iopub.status.idle": "2024-11-07T16:45:34.906767Z", + "shell.execute_reply": "2024-11-07T16:45:34.906211Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [ + { + "data": { + "text/plain": [ + "3" + ] + }, + "execution_count": 10, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# a.sum is the sum of all elements - a unary operation. `.sum()` is a method of the array class because you use it on the array.\n", + "a.sum()" + ] + }, + { + "cell_type": "markdown", + "id": "f0fedf38-dff2-43df-8057-4998d7219e31", + "metadata": {}, + "source": [ + "Q11. Create an array using `np.ones(6).reshape(3,2)`. If we only want to sum each column, how would we do that?" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "id": "84d7b08c-5cfe-4662-b7c2-ee9a1fd5cf1d", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:45:34.911338Z", + "iopub.status.busy": "2024-11-07T16:45:34.911068Z", + "iopub.status.idle": "2024-11-07T16:45:34.921502Z", + "shell.execute_reply": "2024-11-07T16:45:34.920616Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [ + { + "data": { + "text/plain": [ + "array([3., 3.])" + ] + }, + "execution_count": 11, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a = np.ones(6).reshape(3,2)\n", + "a.sum(axis=0)" + ] + }, + { + "cell_type": "markdown", + "id": "c6d39222-c0a5-4013-83ce-182dfab3ea2e", + "metadata": {}, + "source": [ + "### Indexing" + ] + }, + { + "cell_type": "markdown", + "id": "7b2b1a58-8c3e-480f-950a-ccf3a813b8cd", + "metadata": { + "editable": true, + "slideshow": { + "slide_type": "" + }, + "tags": [] + }, + "source": [ + "Q12.\n", + "- Create a 1D array of size 20 where each element is the cube of its index.\n", + "- Print the 5th element of `a`. Hint: your answer should be 64 - remember where we start indexing." + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "id": "f50807ff-0025-4e89-8a17-1ea2988cc367", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:45:34.925203Z", + "iopub.status.busy": "2024-11-07T16:45:34.924904Z", + "iopub.status.idle": "2024-11-07T16:45:34.938051Z", + "shell.execute_reply": "2024-11-07T16:45:34.937079Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [ + { + "data": { + "text/plain": [ + "64" + ] + }, + "execution_count": 12, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Step 1: Create the array\n", + "a = np.arange(20) ** 3\n", + "\n", + "# Step 2: Print the 5th element.\n", + "a[4]" + ] + }, + { + "cell_type": "markdown", + "id": "8793e6ef-144a-440f-aa9e-5b49dc4a583d", + "metadata": {}, + "source": [ + "Q13. Slice the array to get elements from index 3 to index 7 (inclusive)." + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "id": "7c45834d-1a39-4037-9bf1-ca97c8dab09d", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:45:34.942117Z", + "iopub.status.busy": "2024-11-07T16:45:34.941465Z", + "iopub.status.idle": "2024-11-07T16:45:34.955086Z", + "shell.execute_reply": "2024-11-07T16:45:34.953727Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [ + { + "data": { + "text/plain": [ + "array([ 27, 64, 125, 216, 343])" + ] + }, + "execution_count": 13, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a[3:8]" + ] + }, + { + "cell_type": "markdown", + "id": "3be02020-6449-4a8c-a1f6-bf6fafb6ec12", + "metadata": {}, + "source": [ + "Q14. Change every 3rd element to -1. This should give: `[ -1, 1, 8, -1, 64, 125, -1, ... ]`" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "id": "f16bfe38-1f6f-47fd-a7f2-2a9da0333a8b", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:45:34.961165Z", + "iopub.status.busy": "2024-11-07T16:45:34.960785Z", + "iopub.status.idle": "2024-11-07T16:45:34.971049Z", + "shell.execute_reply": "2024-11-07T16:45:34.970204Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [ + { + "data": { + "text/plain": [ + "array([ -1, 1, 8, -1, 64, 125, -1, 343, 512, -1, 1000,\n", + " 1331, -1, 2197, 2744, 3375, 4096, 4913, 5832, 6859])" + ] + }, + "execution_count": 14, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a[:15:3] = -1\n", + "a" + ] + }, + { + "cell_type": "markdown", + "id": "eb80452e-cd4f-4971-825d-86cb4747d9da", + "metadata": {}, + "source": [ + "Q15. Reverse the array and print the result." + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "id": "169e63ce-9d74-4a35-b386-d2bd07bad3a7", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:45:34.976296Z", + "iopub.status.busy": "2024-11-07T16:45:34.975378Z", + "iopub.status.idle": "2024-11-07T16:45:34.987276Z", + "shell.execute_reply": "2024-11-07T16:45:34.986061Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [ + { + "data": { + "text/plain": [ + "array([6859, 5832, 4913, 4096, 3375, 2744, 2197, -1, 1331, 1000, -1,\n", + " 512, 343, -1, 125, 64, -1, 8, 1, -1])" + ] + }, + "execution_count": 15, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "reversed_a = a[::-1]\n", + "reversed_a" + ] + }, + { + "cell_type": "markdown", + "id": "1cd5271c-8a90-49ae-979b-d89575491b01", + "metadata": {}, + "source": [ + "Q16. Create a 3x4 numpy array `b` using `b = np.array([[2 * i + j for j in range(4)] for i in range(3)])`." + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "id": "5536dff6-d6c2-4dab-a4e6-869629e0edeb", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:45:34.991370Z", + "iopub.status.busy": "2024-11-07T16:45:34.990844Z", + "iopub.status.idle": "2024-11-07T16:45:35.005952Z", + "shell.execute_reply": "2024-11-07T16:45:35.003808Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[0 1 2 3]\n", + " [2 3 4 5]\n", + " [4 5 6 7]]\n" + ] + } + ], + "source": [ + "b = np.array([[2 * i + j for j in range(4)] for i in range(3)])\n", + "print(b)" + ] + }, + { + "cell_type": "markdown", + "id": "3983a14f-de1d-490b-b6fd-4f4d7eda14fb", + "metadata": {}, + "source": [ + "Q17. Print the element in the second row and third column. This should be 4." + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "id": "a734ee36-b794-4260-808c-575518b4a34e", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:45:35.010659Z", + "iopub.status.busy": "2024-11-07T16:45:35.009978Z", + "iopub.status.idle": "2024-11-07T16:45:35.021059Z", + "shell.execute_reply": "2024-11-07T16:45:35.020149Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [ + { + "data": { + "text/plain": [ + "4" + ] + }, + "execution_count": 17, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "b[1,2]" + ] + }, + { + "cell_type": "markdown", + "id": "3e4d5ba7-1abe-4285-bd7b-29bca9febbf1", + "metadata": {}, + "source": [ + "Q18. Extract and print the second column as a 1D array." + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "id": "e190b233-124d-40c3-b928-c66f015217df", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:45:35.024197Z", + "iopub.status.busy": "2024-11-07T16:45:35.023920Z", + "iopub.status.idle": "2024-11-07T16:45:35.035750Z", + "shell.execute_reply": "2024-11-07T16:45:35.034822Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [ + { + "data": { + "text/plain": [ + "array([1, 3, 5])" + ] + }, + "execution_count": 18, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "second_col = b[:, 1]\n", + "second_col" + ] + }, + { + "cell_type": "markdown", + "id": "24b839b8-a010-4bd5-afdc-f7046c7acc26", + "metadata": {}, + "source": [ + "Q19. Extract and print a sub-array containing the last two rows." + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "id": "6efa59b9-0bc1-4a8b-ae32-4ffbe75512cb", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:45:35.038908Z", + "iopub.status.busy": "2024-11-07T16:45:35.038379Z", + "iopub.status.idle": "2024-11-07T16:45:35.051161Z", + "shell.execute_reply": "2024-11-07T16:45:35.050287Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [ + { + "data": { + "text/plain": [ + "array([[2, 3, 4, 5],\n", + " [4, 5, 6, 7]])" + ] + }, + "execution_count": 19, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "sub_array = b[1:3, :]\n", + "sub_array" + ] + }, + { + "cell_type": "markdown", + "id": "d4fb0210-2031-4435-bdae-b567a6010c42", + "metadata": {}, + "source": [ + "Q20. Use slicing to replace the last row with the values `[7, 7, 7, 7]`." + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "id": "d2e59188-020a-4c03-a373-9d50b0def22f", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:45:35.054713Z", + "iopub.status.busy": "2024-11-07T16:45:35.054443Z", + "iopub.status.idle": "2024-11-07T16:45:35.068244Z", + "shell.execute_reply": "2024-11-07T16:45:35.067085Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [ + { + "data": { + "text/plain": [ + "array([[0, 1, 2, 3],\n", + " [2, 3, 4, 5],\n", + " [7, 7, 7, 7]])" + ] + }, + "execution_count": 20, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "b[2, :] = [7, 7, 7, 7]\n", + "b" + ] + }, + { + "cell_type": "markdown", + "id": "161545bc-06dd-40cb-b598-36de4f5378e3", + "metadata": {}, + "source": [ + "Q21. Iterate over the elements of the array using the `.flat` attribute and print them." + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "id": "78081cb7-6c73-466b-a736-1aca4c652f49", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:45:35.074455Z", + "iopub.status.busy": "2024-11-07T16:45:35.073677Z", + "iopub.status.idle": "2024-11-07T16:45:35.082625Z", + "shell.execute_reply": "2024-11-07T16:45:35.081523Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "0\n", + "1\n", + "2\n", + "3\n", + "2\n", + "3\n", + "4\n", + "5\n", + "7\n", + "7\n", + "7\n", + "7\n" + ] + } + ], + "source": [ + "for element in b.flat:\n", + " print(element)" + ] + }, + { + "cell_type": "markdown", + "id": "0ea93892-c626-4e4e-b91c-763daf6bb7e1", + "metadata": {}, + "source": [ + "Q22. Create a 3D array `c` using `c = np.array([[[i * 10 + j * 5 + k for k in range(4)] for j in range(3)] for i in range(2)])`" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "id": "15632b1d-f44e-4a1e-9efb-e6fde75e266b", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:45:35.087438Z", + "iopub.status.busy": "2024-11-07T16:45:35.086993Z", + "iopub.status.idle": "2024-11-07T16:45:35.099686Z", + "shell.execute_reply": "2024-11-07T16:45:35.098567Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [ + { + "data": { + "text/plain": [ + "array([[[ 0, 1, 2, 3],\n", + " [ 5, 6, 7, 8],\n", + " [10, 11, 12, 13]],\n", + "\n", + " [[10, 11, 12, 13],\n", + " [15, 16, 17, 18],\n", + " [20, 21, 22, 23]]])" + ] + }, + "execution_count": 22, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "c = np.array([[[i * 10 + j * 5 + k for k in range(4)] for j in range(3)] for i in range(2)])\n", + "c" + ] + }, + { + "cell_type": "markdown", + "id": "d48d62f7-5ccc-4dc6-a441-cac5ebc4cb10", + "metadata": {}, + "source": [ + "Q23. Print all elements of the first layer of the array." + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "id": "53d8f855-bba0-40a4-aeba-2b719b87b363", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:45:35.103756Z", + "iopub.status.busy": "2024-11-07T16:45:35.103053Z", + "iopub.status.idle": "2024-11-07T16:45:35.118641Z", + "shell.execute_reply": "2024-11-07T16:45:35.117258Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [ + { + "data": { + "text/plain": [ + "array([[ 0, 1, 2, 3],\n", + " [ 5, 6, 7, 8],\n", + " [10, 11, 12, 13]])" + ] + }, + "execution_count": 23, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "c[0]" + ] + }, + { + "cell_type": "markdown", + "id": "96fcfb26-8c72-476b-b030-9e1f61a143ab", + "metadata": {}, + "source": [ + "Q24. Use `...` to print the last element of each 1D array contained within c." + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "id": "59fcba5b-3772-4326-9f82-da576e8e6f5d", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:45:35.124400Z", + "iopub.status.busy": "2024-11-07T16:45:35.123593Z", + "iopub.status.idle": "2024-11-07T16:45:35.132851Z", + "shell.execute_reply": "2024-11-07T16:45:35.131940Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [ + { + "data": { + "text/plain": [ + "array([[ 3, 8, 13],\n", + " [13, 18, 23]])" + ] + }, + "execution_count": 24, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "c[..., -1]" + ] + }, + { + "cell_type": "markdown", + "id": "c96b71dd-bb47-41aa-9403-cc51f660aa0d", + "metadata": {}, + "source": [ + "Q25. Modify the first column of the second layer to `[0, 0, 0]`." + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "id": "495e40c1-5584-4e58-9db3-70b380b1fae5", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:45:35.137623Z", + "iopub.status.busy": "2024-11-07T16:45:35.137006Z", + "iopub.status.idle": "2024-11-07T16:45:35.148197Z", + "shell.execute_reply": "2024-11-07T16:45:35.147116Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [ + { + "data": { + "text/plain": [ + "array([[[ 0, 1, 2, 3],\n", + " [ 5, 6, 7, 8],\n", + " [10, 11, 12, 13]],\n", + "\n", + " [[ 0, 11, 12, 13],\n", + " [ 0, 16, 17, 18],\n", + " [ 0, 21, 22, 23]]])" + ] + }, + "execution_count": 25, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "c[1, :, 0] = [0, 0, 0]\n", + "c" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 + Jaspy", + "language": "python", + "name": "jaspy" + }, + "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.9" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/python-data/solutions/ex06b_numpy.ipynb b/python-data/solutions/ex06b_numpy.ipynb new file mode 100644 index 0000000..43f030c --- /dev/null +++ b/python-data/solutions/ex06b_numpy.ipynb @@ -0,0 +1,732 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "93699150-662a-4a21-bc2b-7836c39d0e0d", + "metadata": { + "editable": true, + "slideshow": { + "slide_type": "" + }, + "tags": [] + }, + "source": [ + "# Exercise 6b: numpy (continued)" + ] + }, + { + "cell_type": "markdown", + "id": "0465143d-b368-4fcb-baec-017e5aaf801b", + "metadata": {}, + "source": [ + "## Aim: Get an overview of NumPy and some useful functions." + ] + }, + { + "cell_type": "markdown", + "id": "0364bf4f-20d1-49bc-8e2e-90f636e579ea", + "metadata": {}, + "source": [ + "You can find the teaching resources for this lesson here: https://numpy.org/doc/stable/user/quickstart.html" + ] + }, + { + "cell_type": "markdown", + "id": "b169c5eb-8467-4830-ba53-8707ad9642d0", + "metadata": {}, + "source": [ + "### Issues covered:\n", + "- Shape manipulation: changing shape, stacking, splitting\n", + "- Copies and views" + ] + }, + { + "cell_type": "markdown", + "id": "bd16b618-3891-4613-9257-a3fbaba8f53f", + "metadata": {}, + "source": [ + "## 2. Shape manipulation" + ] + }, + { + "cell_type": "markdown", + "id": "776d6a74-7fd7-4a76-9388-694a241fcfdf", + "metadata": {}, + "source": [ + "### Changing the shape" + ] + }, + { + "cell_type": "markdown", + "id": "34b119db-ac4b-44cb-96a8-ca00e89cb2db", + "metadata": {}, + "source": [ + "Q1. Use the following to create a 3x4 array: \n", + "```\n", + "rg = np.random.default_rng(1)\n", + "a = np.floor(10 * rg.random((3, 4)))\n", + "```\n", + "Then use the `ravel` method to flatten the array and print it." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "addaf639-10ae-402b-a6e8-6dbbdab747f7", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:44:43.926389Z", + "iopub.status.busy": "2024-11-07T16:44:43.925221Z", + "iopub.status.idle": "2024-11-07T16:44:44.456971Z", + "shell.execute_reply": "2024-11-07T16:44:44.455705Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[[5. 9. 1. 9.]\n", + " [3. 4. 8. 4.]\n", + " [5. 0. 7. 5.]]\n" + ] + }, + { + "data": { + "text/plain": [ + "array([5., 9., 1., 9., 3., 4., 8., 4., 5., 0., 7., 5.])" + ] + }, + "execution_count": 1, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "import numpy as np\n", + "rg = np.random.default_rng(1)\n", + "a = np.floor(10 * rg.random((3, 4)))\n", + "print(a)\n", + "a.ravel()" + ] + }, + { + "cell_type": "markdown", + "id": "4d060d03-973b-4916-80d9-29382400419f", + "metadata": {}, + "source": [ + "Q2. Reshape the array so it has the shape (2,6) and print it." + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "ddd29757-7974-4a25-a3ad-34fbe2910a62", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:44:44.460969Z", + "iopub.status.busy": "2024-11-07T16:44:44.460546Z", + "iopub.status.idle": "2024-11-07T16:44:44.467996Z", + "shell.execute_reply": "2024-11-07T16:44:44.467190Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [ + { + "data": { + "text/plain": [ + "array([[5., 9., 1., 9., 3., 4.],\n", + " [8., 4., 5., 0., 7., 5.]])" + ] + }, + "execution_count": 2, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "b = a.reshape(2, 6)\n", + "b" + ] + }, + { + "cell_type": "markdown", + "id": "78cd0758-225c-4b58-8e84-1e4e3872293f", + "metadata": {}, + "source": [ + "Q3. Transpose the array and print it." + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "ff5c18e1-ea8a-4d78-8b6c-38ac268fe6dc", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:44:44.470550Z", + "iopub.status.busy": "2024-11-07T16:44:44.470296Z", + "iopub.status.idle": "2024-11-07T16:44:44.489171Z", + "shell.execute_reply": "2024-11-07T16:44:44.487883Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [ + { + "data": { + "text/plain": [ + "array([[5., 3., 5.],\n", + " [9., 4., 0.],\n", + " [1., 8., 7.],\n", + " [9., 4., 5.]])" + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "c = a.T\n", + "c" + ] + }, + { + "cell_type": "markdown", + "id": "bf99d355-263c-4448-9160-cb433c6297fd", + "metadata": {}, + "source": [ + "Q4. Use the resize method to change the shape of the array to (6,2). Notice the difference between reshape and resize." + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "65805c3d-bfef-4cd2-9a20-d123078f9672", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:44:44.494484Z", + "iopub.status.busy": "2024-11-07T16:44:44.494103Z", + "iopub.status.idle": "2024-11-07T16:44:44.508456Z", + "shell.execute_reply": "2024-11-07T16:44:44.507225Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [ + { + "data": { + "text/plain": [ + "array([[5., 9.],\n", + " [1., 9.],\n", + " [3., 4.],\n", + " [8., 4.],\n", + " [5., 0.],\n", + " [7., 5.]])" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# reshape returns the argument with a modified shape but resize modifies the array itself\n", + "a.resize(6,2)\n", + "a" + ] + }, + { + "cell_type": "markdown", + "id": "0254d87c-8cf2-42e9-9193-fb0a57b99f71", + "metadata": {}, + "source": [ + "Q5. Reshape the array to a shape of (3, -1) and print the reshaped array. Note what `-1` does here." + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "ecd467a6-738c-4b3a-b37a-5f7ded7bb544", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:44:44.514020Z", + "iopub.status.busy": "2024-11-07T16:44:44.513435Z", + "iopub.status.idle": "2024-11-07T16:44:44.532472Z", + "shell.execute_reply": "2024-11-07T16:44:44.530794Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [ + { + "data": { + "text/plain": [ + "array([[5., 9., 1., 9.],\n", + " [3., 4., 8., 4.],\n", + " [5., 0., 7., 5.]])" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "d =a.reshape(3, -1)\n", + "d" + ] + }, + { + "cell_type": "markdown", + "id": "e24b0985-7938-4d08-aa8a-ffe5b6741823", + "metadata": {}, + "source": [ + "### Stacking" + ] + }, + { + "cell_type": "markdown", + "id": "9150a86b-b60c-4235-99f1-df8a72ea383d", + "metadata": {}, + "source": [ + "Q6.\n", + "- Write a function `stack_arrays` that takes two 2D arrays `a` and `b`, an axis argument and returns the arrays stacked along the specified axis. The function should handle the following cases:\n", + " - Vertical stacking (`axis=0`): Stack the arrays along rows\n", + " - Horizontal stacking (`axis=1`): Stack the arrays along columns\n", + " - Column stacking (`axis=column`): Stack 1D arrays as columns of a 2D array if both a and b are 1D, if they are 2D stack them horizontally\n", + " - If `axis` is set to any other value raise a `ValueError`\n", + "- Once you're happy with your function, try the test cases in the solutions to check your working!" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "21527484-619e-47c0-a222-092ee88fb478", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:44:44.538232Z", + "iopub.status.busy": "2024-11-07T16:44:44.537362Z", + "iopub.status.idle": "2024-11-07T16:44:44.559570Z", + "shell.execute_reply": "2024-11-07T16:44:44.558050Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [] + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Vertical stacking:\n", + " [[9. 7.]\n", + " [5. 2.]\n", + " [1. 9.]\n", + " [5. 1.]]\n", + "\n", + "Horizontal stacking:\n", + " [[9. 7. 1. 9.]\n", + " [5. 2. 5. 1.]]\n", + "\n", + "Column stacking (1D arrays):\n", + " [[4. 3.]\n", + " [2. 8.]]\n" + ] + } + ], + "source": [ + "import numpy as np\n", + "\n", + "def stack_arrays(a, b, axis):\n", + " if axis == 0:\n", + " return np.vstack((a, b))\n", + " elif axis == 1:\n", + " return np.hstack((a,b))\n", + " elif axis == 'column':\n", + " return np.column_stack((a,b))\n", + " else:\n", + " raise ValueError(\"Invalid axis specified. Use 0, 1 or 'column'.\")\n", + "\n", + "# Test cases\n", + "a = np.array([[9,7], [5,2]])\n", + "b = np.array([[1., 9.], [5., 1.]])\n", + "c = np.array([4., 2.])\n", + "d = np.array([3., 8.])\n", + "\n", + "# Vertical stacking\n", + "print(\"Vertical stacking:\\n\", stack_arrays(a, b, axis=0))\n", + "\n", + "# Horizontal stacking\n", + "print(\"\\nHorizontal stacking:\\n\", stack_arrays(a, b, axis=1))\n", + "\n", + "# Column stacking for 1D arrays\n", + "print(\"\\nColumn stacking (1D arrays):\\n\", stack_arrays(c, d, axis='column'))" + ] + }, + { + "cell_type": "markdown", + "id": "54b6c868-dfc8-4113-bf8c-4ec92b72d6c4", + "metadata": {}, + "source": [ + "### Splitting" + ] + }, + { + "cell_type": "markdown", + "id": "9150e1f6-639b-4bce-9777-c35e96e49de8", + "metadata": {}, + "source": [ + "Q7.\n", + "Given the following 2D array `b`:\n", + "```\n", + "rg = np.random.default_rng(42)\n", + "b = np.floor(10 * rg.random((2, 10)))\n", + "```\n", + "- Split the array equally using `np.hsplit` into 5 parts along the horizontal axis. Assign the resulting sub-arrays to a variable named `equal_splits`\n", + "- Split the array after the second and fifth columns using `np.hsplit`. Assign the resulting sub-arrays to a variable called `column_splits`." + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "id": "c7d0c083-8f9d-4431-a68e-a57ee23fa4ff", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:44:44.565408Z", + "iopub.status.busy": "2024-11-07T16:44:44.564948Z", + "iopub.status.idle": "2024-11-07T16:44:44.582739Z", + "shell.execute_reply": "2024-11-07T16:44:44.581210Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Equal Splits: [array([[7., 4.],\n", + " [3., 9.]]), array([[8., 6.],\n", + " [6., 8.]]), array([[0., 9.],\n", + " [4., 2.]]), array([[7., 7.],\n", + " [5., 0.]]), array([[1., 4.],\n", + " [8., 6.]])]\n", + "Column Splits: [array([[7., 4.],\n", + " [3., 9.]]), array([[8., 6., 0.],\n", + " [6., 8., 4.]]), array([[9., 7., 7., 1., 4.],\n", + " [2., 5., 0., 8., 6.]])]\n" + ] + } + ], + "source": [ + "rg = np.random.default_rng(42)\n", + "b = np.floor(10 * rg.random((2, 10)))\n", + "\n", + "# Step 1: Split array b into 5 equal parts\n", + "equal_splits = np.hsplit(b, 5)\n", + "\n", + "# Step 2: Split array after second and fifth columns\n", + "column_splits = np.hsplit(b, (2, 5))\n", + "\n", + "# Print results\n", + "print(\"Equal Splits:\", equal_splits)\n", + "print(\"Column Splits:\", column_splits)" + ] + }, + { + "cell_type": "markdown", + "id": "f5c2d6e1-e758-459c-bd22-192651a96507", + "metadata": {}, + "source": [ + "## 3. Copies and views" + ] + }, + { + "cell_type": "markdown", + "id": "dff98f88-d2e0-4b90-ba24-9752ffe36888", + "metadata": {}, + "source": [ + "Q8. Let's demonstrate No Copy:\n", + "- Write a function `test_no_copy()` that:\n", + " - Creates a `3x3` Numpy array `a`.\n", + " - Assigns `b=a` and checks if modifying `b` affects `a`.\n", + " - Returns `True` if `b` is a reference to `a` i.e. no copy is made, and `False` otherwise\n", + " - Hint: use `is` to verify if `a` and `b` are the same object." + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "id": "509b0f88-170f-49de-9e25-672bde58738e", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:44:44.588398Z", + "iopub.status.busy": "2024-11-07T16:44:44.587869Z", + "iopub.status.idle": "2024-11-07T16:44:44.603287Z", + "shell.execute_reply": "2024-11-07T16:44:44.602046Z" + }, + "scrolled": true, + "slideshow": { + "slide_type": "" + }, + "tags": [] + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Testing no copy behavior: True\n" + ] + } + ], + "source": [ + "def test_no_copy():\n", + " a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n", + " b = a\n", + " b[0, 0] = 999\n", + " return b is a # Check if 'b' is a reference to 'a'\n", + "\n", + "print(\"Testing no copy behavior:\", test_no_copy()) # Expected: True" + ] + }, + { + "cell_type": "markdown", + "id": "c1094086-cb82-4541-b9a1-811773050bf8", + "metadata": {}, + "source": [ + "Q9. Let's demonstrate Shallow Copy:\n", + "- Write a function `test_shallow_copy()` that:\n", + " - Creates a `3x3` Numpy array `a`.\n", + " - Creates a shallow copy of `a` using `a.view()` and assigns it to `c`.\n", + " - Modifies an element in `c` and checks if the change is reflected in `a`\n", + " - Verifies that `a` and `c` are not the same object but share data\n", + " - Returns `True` if the modification in `c` also modifies `a` and `False` otherwise\n", + " - Hint: Use `is` to confirm `a` and `c` are different objects, and `c.base is a` to confirm shared data. " + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "id": "4788a3fb-9483-4417-9e6d-52a5cc15de64", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:44:44.609160Z", + "iopub.status.busy": "2024-11-07T16:44:44.608733Z", + "iopub.status.idle": "2024-11-07T16:44:44.631397Z", + "shell.execute_reply": "2024-11-07T16:44:44.629854Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Testing shallow copy behavior: True\n" + ] + } + ], + "source": [ + "def test_shallow_copy():\n", + " a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n", + " c = a.view()\n", + " c[0, 0] = 999\n", + " return c is not a and c.base is a # Verify 'c' is a view of 'a'\n", + "\n", + "print(\"Testing shallow copy behavior:\", test_shallow_copy()) # Expected: True" + ] + }, + { + "cell_type": "markdown", + "id": "fd0dc68d-9a11-4f86-a4c9-c1e8fd10946c", + "metadata": {}, + "source": [ + "Q10. Let's demonstrate Deep Copy: \n", + "- Write a function `test_deep_copy()`that:\n", + " - Creates a `3x3` Numpy array `a`\n", + " - Creates a deep copy of `a` using `a.copy()` and assigns it to `d`\n", + " - Modifies an element in `d` and checks if the change is reflected in `a`\n", + " - Verifies that `a` and `d` do not share data\n", + " - Returns `True` if `a` and `d` do not share data and `False` if they do. " + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "id": "899f1587-f732-487a-a06c-b4f58d9d9af7", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:44:44.637952Z", + "iopub.status.busy": "2024-11-07T16:44:44.637302Z", + "iopub.status.idle": "2024-11-07T16:44:44.657136Z", + "shell.execute_reply": "2024-11-07T16:44:44.655518Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [] + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Testing deep copy behavior: True\n" + ] + } + ], + "source": [ + "def test_deep_copy():\n", + " a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n", + " d = a.copy()\n", + " d[0, 0] = 999\n", + " return d.base is None and np.any(a != d) # Check if 'd' is a true deep copy\n", + "\n", + "print(\"Testing deep copy behavior:\", test_deep_copy()) # Expected: True" + ] + }, + { + "cell_type": "markdown", + "id": "d2493f55-f912-44bf-8ea2-90bb588d490a", + "metadata": { + "editable": true, + "slideshow": { + "slide_type": "" + }, + "tags": [] + }, + "source": [ + "Q11. Let's demonstrate Memory Management: \n", + "- Write a function `memory_management_example()` that:\n", + " - Creates a large array `a` of 10 million elements\n", + " - Creates a slice of `a` containing the first 10 elements and assigns it to `b`\n", + " - Deletes `a` and observes what happens to `b`\n", + " - Creates another slice of `a` containing the first 1- elements but it copies it deeply this time assigning it to `c`\n", + " - Deletes `a` and observes if `c` is still accessible\n", + " - Returns `True` if `b` cannot be accessed after deleting `a`, but `c` can and `False` otherwise\n", + " - Hint: use a try-except block to handle errors from accessing `b` after deleting `a`" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "id": "91110ee3-d12d-41ba-8394-82b32f5f2e6f", + "metadata": { + "editable": true, + "execution": { + "iopub.execute_input": "2024-11-07T16:44:44.663498Z", + "iopub.status.busy": "2024-11-07T16:44:44.662919Z", + "iopub.status.idle": "2024-11-07T16:44:44.725925Z", + "shell.execute_reply": "2024-11-07T16:44:44.724218Z" + }, + "slideshow": { + "slide_type": "" + }, + "tags": [ + "clear_answer_cell" + ] + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Testing memory management example: False\n" + ] + } + ], + "source": [ + "def memory_management_example():\n", + " a = np.arange(int(1e7))\n", + " b = a[:10]\n", + " del a\n", + " try:\n", + " b_sum = b.sum() # Check if 'b' is accessible after deleting 'a'\n", + " except NameError:\n", + " b_accessible = False\n", + " else:\n", + " b_accessible = True\n", + "\n", + " a = np.arange(int(1e7)) # Re-create 'a' for the next test\n", + " c = a[:10].copy()\n", + " del a\n", + " try:\n", + " c_sum = c.sum() # Check if 'c' is accessible after deleting 'a'\n", + " except NameError:\n", + " c_accessible = False\n", + " else:\n", + " c_accessible = True\n", + "\n", + " return not b_accessible and c_accessible\n", + "\n", + "print(\"Testing memory management example:\", memory_management_example()) # Expected: True" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 + Jaspy", + "language": "python", + "name": "jaspy" + }, + "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.9" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +}