{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "l15-c000",
   "metadata": {},
   "source": [
    "# Lecture 17 - Collections 3: Copying, searching, and sorting\n",
    "\n",
    "**Authors:** Fiona McNeill, Matteo Degiacomi, Rayo Verweij, and Nigel Topham\n",
    "\n",
    "## Introduction\n",
    "\n",
    "We're finishing up our discussion of collections with deep dives into three aspects we've only lightly touched upon so far: copying, searching, and sorting. In doing so, we'll trace a few algorithms and compare the work involved.\n",
    "\n",
    "### Learning outcomes\n",
    "\n",
    "In this notebook, we'll discuss:\n",
    "\n",
    "- the difference between comparing equality and identity of objects;\n",
    "- using the `is` operator in Python;\n",
    "- creating deep copies using the `copy` module;\n",
    "- implementing linear and binary search and recognising the strengths and limitations of both;\n",
    "- using Python's `sorted()` and `.sort()`, including using a function as a sort key;\n",
    "- tracing and implementing bubble sort and insertion sort; and\n",
    "- comparing algorithms by counting comparisons and movements.\n",
    "\n",
    "### Using the notebook\n",
    "\n",
    "Remember, this notebook is _yours_! You can edit each cell, for example by adding new examples or changing values to see what happens. Feel free to experiment!\n",
    "\n",
    "<details>\n",
    "<summary>Click to expand</summary>\n",
    "\n",
    "A common approach for learning how to read and write code in a structured way is called **PRIMM**:\n",
    "1. **Predict**: before running the code, look at it - do you understand each line? What do you think will happen?\n",
    "2. **Run**: now run the code and see what output you get.\n",
    "3. **Investigate**: did it go as you thought it would? If not, can you figure out why?\n",
    "4. **Modify**: now change the code and once again try to predict the output. If you got it wrong the first time, did you get it right now?\n",
    "5. **Make**: finally, try to write your own program from scratch using the skills you learned.\n",
    "\n",
    "You can apply steps 1-4 to each code cell in the notebook and many will have prediction prompts to help you get started. In addition, there will be challenges that ask you to put everything together yourself and execute step 5. There will often be multiple ways to solve these, but each challenge has a potential answer listed.\n",
    "\n",
    "</details>\n",
    "\n",
    "### Navigating the notebook\n",
    "\n",
    "A Jupyter notebook can be operated with your keyboard. Here is a **cheat sheet**:\n",
    "\n",
    "<details>\n",
    "<summary>Click to expand</summary>\n",
    "\n",
    "- To run the selected cell and move to the next cell, press <kbd>&#x21E7; Shift</kbd> + <kbd>&#x23ce; Enter</kbd>.\n",
    "- To run the selected cell and keep focus there, press <kbd>⌃ Ctrl</kbd> + <kbd>&#x23ce; Enter</kbd>.\n",
    "- To create a cell under the one currently highlighted, press <kbd>B</kbd>;\n",
    "- To delete the currently highlighted cell, press <kbd>D</kbd> twice (be careful with this one!) or press <kbd>X</kbd> to cut it;\n",
    "- To get help for a specific function, place the cursor within the function's brackets, hold <kbd>&#x21E7; Shift</kbd>, and press <kbd>&#x21E5; Tab</kbd>.\n",
    "\n",
    "</details>\n",
    "\n",
    "Watch out: **code cells remember what happened in cells before**. So, especially in the more complicated notebooks later down the line, make sure to always run **every** cell from top to bottom, as one might rely on a piece of code that came before it! If your results become confusing, use **Kernel > Restart Kernel** and then rerun all the completed cells in order.\n",
    "\n",
    "### Further reading and practice\n",
    "\n",
    "- Official Python documentation: [Sorting Techniques](https://docs.python.org/3/howto/sorting.html) - read \"Sorting Basics\", \"Key Functions\", \"Ascending and Descending\", and \"Sort Stability\". The `operator` helpers and advanced sorting recipes are optional.\n",
    "- W3Schools: [`is` keyword](https://www.w3schools.com/python/ref_keyword_is.asp), [Binary search](https://www.w3schools.com/dsa/dsa_algo_binarysearch.php), [Sort lists](https://www.w3schools.com/python/python_lists_sort.asp), [Bubble sort](https://www.w3schools.com/dsa/dsa_algo_bubblesort.php), and [Insertion sort](https://www.w3schools.com/dsa/dsa_algo_insertionsort.php).\n",
    "- Helsinki Python MOOC: [References](https://programming-26.mooc.fi/part-5/2-references) and [Functions as arguments](https://programming-26.mooc.fi/part-12/1-functions-as-arguments). Note that both go into a lot more depth than what we discuss here."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "35ccef64",
   "metadata": {},
   "source": [
    "## 1. Equality and identity"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1cc42978",
   "metadata": {},
   "source": [
    "In Lecture 5, when we started our discussion of collections, we spoke briefly about **mutability**, the idea that collection values can be updated after they were created. This means that two names can refer to the same object: they are **aliases**, and updating one will update the other.\n",
    "\n",
    "**Predict:** What will each list print? If you've forgotten, go back to the end of Lecture 5 to check!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "78d5016d",
   "metadata": {},
   "outputs": [],
   "source": [
    "original = [1, 2]\n",
    "alias = original\n",
    "\n",
    "alias.append(3)\n",
    "print(original)\n",
    "print(alias)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3b194159",
   "metadata": {},
   "source": [
    "Now, in Python, there are actually two different ways to check whether two variables are equal.\n",
    "\n",
    "Using `==`, as we have done so far, checks whether the *values* assigned to a variable are equal.\n",
    "\n",
    "By contrast, using the `is` operator checks whether two names refer to the *same object*.\n",
    "\n",
    "There is a very subtle difference - see if you can figure it out in the next example.\n",
    "\n",
    "**Predict:** Can you determine what each comparison will print?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2afee8bf",
   "metadata": {},
   "outputs": [],
   "source": [
    "original = [1, 2]\n",
    "alias = original\n",
    "separate = [1, 2]\n",
    "\n",
    "print(original == alias)\n",
    "print(original is alias)\n",
    "print(original == separate)\n",
    "print(original is not separate)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "507af784",
   "metadata": {},
   "source": [
    "`original`, `alias`, and `separate` all point to a list with value `[1, 2]`. However, `original` and `alias` point to the *same* list in memory, whereas `separate` points to a *different* list in memory.\n",
    "\n",
    "This means that changing `original` also affects what we see through `alias`, while `separate` would remain unchanged.\n",
    "\n",
    "Note: **only use `is` when comparing collections**. When creating immutable objects, Python sometimes reuses objects internally to save memory, so `is` is not a reliable way to compare their values. For those, use `==` instead.\n",
    "\n",
    "For collections, however, `is` can be very useful to check whether two identical-looking ones are actually the same object or simply happen to look identical."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8d37ae54",
   "metadata": {},
   "outputs": [],
   "source": [
    "original = [1, 2]\n",
    "alias = original\n",
    "separate = [1, 2]\n",
    "\n",
    "original.append(3)\n",
    "print(original)\n",
    "print(alias)\n",
    "print(separate)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1b8f933e",
   "metadata": {},
   "source": [
    "`is` is also commonly used to compare values to `None`, if you ever need to."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0380f46a",
   "metadata": {},
   "outputs": [],
   "source": [
    "result = None\n",
    "print(result is None)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "13f89d30",
   "metadata": {},
   "source": [
    "### Shallow and deep copies\n",
    "\n",
    "As discussed in Lecture 5 as well, a collection's `.copy()` method makes a **shallow copy**: it only creates a new outer collection, but its items still refer to the original objects. In a two-dimensional list, for example, each rows still refer to the list objects inside of the original list.\n",
    "\n",
    "**Predict:** Do `grid` and `shallow` refer to the same outer list? What about the lists inside of them? What happens to `grid` when we change an item inside `shallow`?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6367c1ed",
   "metadata": {},
   "outputs": [],
   "source": [
    "grid = [[1, 2], [3, 4]]\n",
    "shallow = grid.copy()\n",
    "\n",
    "print(shallow is grid)\n",
    "print(shallow[0] is grid[0])\n",
    "\n",
    "shallow[0][0] = 99\n",
    "print(\"Original:\", grid)\n",
    "print(\"Shallow copy:\", shallow)\n",
    "\n",
    "shallow.append([5, 6])\n",
    "print(\"After appending to the copy:\", grid, shallow)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "96e034dc",
   "metadata": {},
   "source": [
    "Sometimes, however, we'd rather have a **deep copy**, in which each internal object is copied over as well. Thankfully, the Python standard library contains a `copy` module with more advanced copying tools, including a `deepcopy()` function. For this grid of lists and numbers, it lets us change any copied row without changing the original.\n",
    "\n",
    "**Predict:** What happens to `grid` now, when we update `independent`?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dffaf0da",
   "metadata": {},
   "outputs": [],
   "source": [
    "import copy\n",
    "\n",
    "grid = [[1, 2], [3, 4]]\n",
    "independent = copy.deepcopy(grid)\n",
    "print(independent[0] is grid[0])\n",
    "\n",
    "independent[0][0] = 99\n",
    "print(\"Original:\", grid)\n",
    "print(\"Deep copy:\", independent)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b8573d59",
   "metadata": {},
   "source": [
    "<div class=\"alert alert-success\">\n",
    "<b>Try it yourself: keep the original seating plan</b>\n",
    "\n",
    "You've been given an empty seating chart for a (tiny) cinema. Make a copy in which you can reserve the first seat *without* changing `seats`. Show that the outer lists and their first rows are different objects and check that the original is unchanged.\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6dcfa813",
   "metadata": {},
   "outputs": [],
   "source": [
    "seats = [[\"free\", \"free\"], [\"free\", \"free\"]]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "85ede420",
   "metadata": {},
   "source": [
    "<details><summary><b>Click for a possible solution</b></summary>\n",
    "\n",
    "A shallow copy would still share its rows with `seats`, so we need to make a deep copy instead.\n",
    "\n",
    "```python\n",
    "import copy\n",
    "\n",
    "seats = [[\"free\", \"free\"], [\"free\", \"free\"]]\n",
    "reserved = copy.deepcopy(seats)\n",
    "reserved[0][0] = \"booked\"\n",
    "\n",
    "assert reserved is not seats\n",
    "assert reserved[0] is not seats[0]\n",
    "assert seats == [[\"free\", \"free\"], [\"free\", \"free\"]]\n",
    "print(reserved)\n",
    "```\n",
    "</details>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a0eca500",
   "metadata": {},
   "source": [
    "## 2. Searching in collections"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-c001",
   "metadata": {},
   "source": [
    "Fantastic! Now that we have a deeper understanding of copying collections, let's move on to searching *within* them.\n",
    "\n",
    "Remember that we can use `in` to ask whether a collection contains something. Note again that when using it on a dictionary, `in` its *keys*; use `.values()` to look among the values instead.\n",
    "\n",
    "**Predict:** Which of the following checks return `True`?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l15-c002",
   "metadata": {},
   "outputs": [],
   "source": [
    "rooms = [\"G.07\", \"2.12\", \"3.01\"]\n",
    "capacities = {\"G.07\": 120, \"2.12\": 40}\n",
    "\n",
    "print(\"2.12\" in rooms)\n",
    "print(\"G.07\" in capacities)\n",
    "print(120 in capacities)\n",
    "print(120 in capacities.values())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-c003",
   "metadata": {},
   "source": [
    "Just knowing whether a collection has an item is not always enough, however. Sometimes we might want the position of an item, or a whole matching record.\n",
    "\n",
    "We can use `list.index(value)` to find the index of the first occurrence of `value` in `list`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fb82931d",
   "metadata": {},
   "outputs": [],
   "source": [
    "pastries = [\"croissant\", \"chocolatine\", \"eclair\"]\n",
    "print(pastries.index(\"chocolatine\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f4e49477",
   "metadata": {},
   "source": [
    "A **linear search** examines items one at a time until it finds a match or reaches the end. We have seen many of these already using loops.\n",
    "\n",
    "Remember, `enumerate()` supplies `(index, item)` pairs, which we can unpack into two variables in a loop. `return` stops the search at the first match, and if the loop ends without one, the function returns `None`.\n",
    "\n",
    "**Predict:** What position does `\"Cara\"` have? What happens if we search for a name that isn't in the list?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l15-c004",
   "metadata": {},
   "outputs": [],
   "source": [
    "def linear_search(items, target):\n",
    "    for index, item in enumerate(items):\n",
    "        if item == target:\n",
    "            return index\n",
    "    return None\n",
    "\n",
    "names = [\"Aisha\", \"Ben\", \"Cara\", \"Dev\"]\n",
    "print(linear_search(names, \"Cara\"))\n",
    "print(linear_search(names, \"Zoe\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-c005",
   "metadata": {},
   "source": [
    "Remember that 0 counts as false-y in Python!\n",
    "\n",
    "**Predict:** What is the logic error in the following piece of code?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ccc67f01",
   "metadata": {},
   "outputs": [],
   "source": [
    "position = linear_search(\"Aisha\")\n",
    "\n",
    "# This will not work!\n",
    "if position:\n",
    "\tprint(\"The name is in the list!\")\n",
    "else:\n",
    "\tprint(\"The name could not be found!\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b909bcfd",
   "metadata": {},
   "source": [
    "We'll need to explicitly check that the result of the function is `None`, which we can do with our new `is` operator."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c820092b",
   "metadata": {},
   "outputs": [],
   "source": [
    "position = linear_search(\"Aisha\")\n",
    "\n",
    "# Use this instead!\n",
    "if position is not None:\n",
    "\tprint(\"The name is in the list!\")\n",
    "else:\n",
    "\tprint(\"The name could not be found!\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-c006",
   "metadata": {
    "tags": [
     "exercise"
    ]
   },
   "source": [
    "<div class=\"alert alert-success\">\n",
    "<b>Try it yourself: search a list of records</b>\n",
    "\n",
    "Write `find_by_code(records, target)` for the dictionaries below. Return the first matching dictionary, or `None` if the code is absent. Test both outcomes. The list does not need to be in any particular order.\n",
    "</div>\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l15-c007",
   "metadata": {
    "tags": [
     "exercise"
    ]
   },
   "outputs": [],
   "source": [
    "records = [{\"code\": \"IP\", \"room\": \"G.07\"}, {\"code\": \"CS\", \"room\": \"2.12\"}]\n",
    "# Define and call find_by_code.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-c008",
   "metadata": {
    "tags": [
     "solution"
    ]
   },
   "source": [
    "<details>\n",
    "<summary><b>Click for a possible solution</b></summary>\n",
    "\n",
    "```python\n",
    "def find_by_code(records, target):\n",
    "    for record in records:\n",
    "        if record[\"code\"] == target:\n",
    "            return record\n",
    "    return None\n",
    "\n",
    "print(find_by_code(records, \"CS\"))\n",
    "print(find_by_code(records, \"AI\"))\n",
    "```\n",
    "</details>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-c009",
   "metadata": {},
   "source": [
    "### Binary search\n",
    "\n",
    "Linear search is easy to implement but not always the most efficient. Say your list is 1,000,000 items long - if the item you want to find is the last one in the list, this means you have to access 1,000,000 items. Can we do this more efficiently?\n",
    "\n",
    "Imagine your bike was stolen and you're looking through CCTV footage of the bike rack to see at which point it was taken. You could sit and watch everything from start to finish. You could also, however, start in the middle. If the bike is still there, you know that you only have to look at the second half of the camera footage, and can ignore the first half. If the bike is gone, however, you know you only have to look at the first half. With just one check you've just eliminated half of the list!\n",
    "\n",
    "You can then do this again with the half that you had, to eliminate a quarter. Once again, to eliminate an eighth. This process is called **binary search**: compare your target with the middle item and then continue in the half where the target could still be.\n",
    "\n",
    "Binary search can be a *lot* faster than linear search. However, it has one important limitation: it only works when the sequence is *sorted in the same order as the comparisons*. For example, a list of words should be sorted alphabetically, or camera footage should be available in the sequence that it was recorded. This requirement is a *precondition* of the algorithm.\n",
    "\n",
    "**Predict:** Track the following binary search algorithm step-by-step. For target 25 in the list below, which item is checked first? Which half can then be discarded?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l15-c010",
   "metadata": {},
   "outputs": [],
   "source": [
    "def binary_search(items, target):\n",
    "    low = 0\n",
    "    high = len(items) - 1\n",
    "\n",
    "    while low <= high:\n",
    "        middle = (low + high) // 2\n",
    "        candidate = items[middle]\n",
    "        if candidate == target:\n",
    "            return middle\n",
    "        if candidate < target:\n",
    "            low = middle + 1\n",
    "        else:\n",
    "            high = middle - 1\n",
    "    return None\n",
    "\n",
    "values = [3, 8, 12, 17, 25, 31, 44]\n",
    "print(binary_search(values, 25))\n",
    "print(binary_search(values, 26))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-c011",
   "metadata": {},
   "source": [
    "The answer for 25 is index 4. For 26, the remaining region eventually becomes empty and the result is `None`.\n",
    "\n",
    "Trace the algorithm a couple of times so you get a feel for it. For example, work through target 31. You'd start with `low = 0`, `high = 6`, and `middle = 3`. After checking 17, the remaining boundaries are 4 and 6. Which value is in their middle? What happens after that?\n",
    "\n",
    "If you find it difficult to wrap your head around it, use the algorithm below, which prints a message each step of the way (but is otherwise exactly the same).\n",
    "\n",
    "Try an unsorted list afterwards. Binary search can miss a value that is present, because a comparison no longer tells us which half is safe to discard. With duplicates in a sorted list, this version may return any matching index."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l15-c012",
   "metadata": {},
   "outputs": [],
   "source": [
    "def binary_search_with_trace(items, target):\n",
    "    low = 0\n",
    "    high = len(items) - 1\n",
    "\n",
    "    while low <= high:\n",
    "        middle = (low + high) // 2\n",
    "        print(f\"Searching indices {low}..{high}; checking {middle}\")\n",
    "        if items[middle] == target:\n",
    "            return middle\n",
    "        if items[middle] < target:\n",
    "            low = middle + 1\n",
    "        else:\n",
    "            high = middle - 1\n",
    "    return None\n",
    "\n",
    "print(binary_search_with_trace([3, 8, 12, 17, 25, 31, 44], 31))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8de7428a",
   "metadata": {},
   "source": [
    "Finally, try searching in an unsorted list. Now, binary search might miss a value, because the comparisons no longer tell us which half is safe to discard."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-c013",
   "metadata": {
    "tags": [
     "exercise"
    ]
   },
   "source": [
    "<div class=\"alert alert-success\">\n",
    "<b>Try it yourself: check the boundaries</b>\n",
    "\n",
    "Let's make sure our code is robust. Write at least six assertions for `binary_search()`:\n",
    "\n",
    "- an empty list;\n",
    "- a one-item list with a present and an absent target;\n",
    "- the first and last items of a longer list; and\n",
    "- an absent value between two items.\n",
    "\n",
    "Use `is None` for testing missing results.\n",
    "</div>\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l15-c014",
   "metadata": {
    "tags": [
     "exercise"
    ]
   },
   "outputs": [],
   "source": [
    "# Your tests here!\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-c015",
   "metadata": {
    "tags": [
     "solution"
    ]
   },
   "source": [
    "<details>\n",
    "<summary><b>Click for a possible solution</b></summary>\n",
    "\n",
    "```python\n",
    "assert binary_search([], 1) is None\n",
    "assert binary_search([5], 5) == 0\n",
    "assert binary_search([5], 4) is None\n",
    "assert binary_search([1, 3, 5, 7], 1) == 0\n",
    "assert binary_search([1, 3, 5, 7], 7) == 3\n",
    "assert binary_search([1, 3, 5, 7], 4) is None\n",
    "```\n",
    "</details>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4d0748d1",
   "metadata": {},
   "source": [
    "## 3. Sorting collections"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-c016",
   "metadata": {},
   "source": [
    "For binary search to work, we need our lists to be sorted. Conveniently, Python has several sorting methods built in.\n",
    "\n",
    "`sorted()` is a built-in function that works on both lists and tuples, returning a new sorted list and leaving the original collection alone. Note that it only creates a shallow copy of the original collection, and always returns a list (even if you gave it a tuple as input).\n",
    "\n",
    "`.sort()` is a list method that changes (mutates) the list *in-place*. It returns `None`.\n",
    "\n",
    "Both accept the keyword argument `reverse=True` to put larger values first.\n",
    "\n",
    "**Predict:** What is assigned to `result1` and `result2` below? Which of the lists keeps its original order?\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l15-c017",
   "metadata": {},
   "outputs": [],
   "source": [
    "original = [31, 8, 17, 3, 25]\n",
    "\n",
    "copied = original.copy()\n",
    "result1 = copied.sort()\n",
    "print(copied)\n",
    "print(result1)\n",
    "\n",
    "result2 = sorted(original, reverse=True)\n",
    "print(original)\n",
    "print(result2)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-c018",
   "metadata": {},
   "source": [
    "Surprised by the output of `result1`? Remember, `.sort()` updates the original value and returns `None`! If you want a new list to assign to a variable, use `sorted()`.\n",
    "\n",
    "### Passing functions as arguments\n",
    "\n",
    "Suppose you have a list containing dictionaries, each with a name and a mark. We might want to sort this list by name or by mark, but how would we give `sorted()` access to the items inside of each dictionary?\n",
    "\n",
    "We can supply `sorted()` with a **key function**, a function that takes an item and returns the value to sort by. We can then *pass the function itself as an argument* to `sorted()`. Take a look at the following piece of code:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l15-c019",
   "metadata": {},
   "outputs": [],
   "source": [
    "records = [\n",
    "    {\"name\": \"Aisha\", \"mark\": 72},\n",
    "    {\"name\": \"Ben\", \"mark\": 68},\n",
    "    {\"name\": \"Cara\", \"mark\": 81},\n",
    "]\n",
    "\n",
    "def mark_of(record):\n",
    "    return record[\"mark\"]\n",
    "\n",
    "ordered_records = sorted(records, key=mark_of)\n",
    "print(ordered_records)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "caf8c2cb",
   "metadata": {},
   "source": [
    "While this might seem unintuitive, in Python, *functions are just objects*, just like strings, ints, lists, et cetera. They have type `function` and can be passed as arguments by their name just like any other function.\n",
    "\n",
    "*Calling* a function requires putting parentheses behind it, but using a function's name without them just refers to the function itself. We have, actually, seen this before: when using `help()`, we passed the function's name, instead of calling it.\n",
    "\n",
    "We do the same here, in `key=mark_of`. `mark_of` is a very basic function that just returns the `mark` from a `record`. `sorted()` calls it once for each record and uses the returned marks for comparison. This allows us to apply many different ordering rules.\n",
    "\n",
    "Note that writing `key=mark_of()`, *with* parentheses, would call the function immediately and break the code."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-c020",
   "metadata": {
    "tags": [
     "exercise"
    ]
   },
   "source": [
    "<div class=\"alert alert-success\">\n",
    "<b>Try it yourself: choose a sort key</b>\n",
    "\n",
    "Sort the `(module, mark)` tuples below by mark from highest to lowest, using a named key function. Keep the original list is unchanged.\n",
    "\n",
    "Secondly, add another module with the same mark as IP and see what happens to their relative order.\n",
    "</div>\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l15-c021",
   "metadata": {
    "tags": [
     "exercise"
    ]
   },
   "outputs": [],
   "source": [
    "results = [(\"IP\", 74), (\"CriSP\", 68), (\"CAFI\", 81)]\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-c022",
   "metadata": {
    "tags": [
     "solution"
    ]
   },
   "source": [
    "<details><summary><b>Click for a possible solution</b></summary>\n",
    "\n",
    "Python's sort is **stable**, meaning that items with equal keys keep the order they had in the input.\n",
    "\n",
    "```python\n",
    "results = [(\"IP\", 74), (\"CriSP\", 68), (\"CAFI\", 81), (\"FC\", 74)]\n",
    "before = results.copy()\n",
    "\n",
    "def mark_of(result):\n",
    "    return result[1]\n",
    "\n",
    "ordered = sorted(results, key=mark_of, reverse=True)\n",
    "\n",
    "assert results == before\n",
    "print(ordered)\n",
    "# IP stays before FC - their keys are equal so input order is preserved\n",
    "```\n",
    "</details>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8bf34e58",
   "metadata": {},
   "source": [
    "## 4. Sorting manually"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-c023",
   "metadata": {},
   "source": [
    "While Python's sorting algorithms are very adequate, let's look at two ways we could implement a sorting algorithm ourselves: *bubble sort* and *insertion sort*. There are many more sorting algorithms, some of which you will see in higher-level courses, but for now these form a good start.\n",
    "\n",
    "### Bubble sort\n",
    "\n",
    "**Bubble sort** compares two neighbouring items and swaps them when the left one is larger. After one pass through the list, the largest item has reached the end. On the next pass, we can leave that final item alone, making our passes shorter and shorter.\n",
    "\n",
    "For example, one pass through `[5, 1, 4, 2]` gives:\n",
    "\n",
    "```text\n",
    "[1, 5, 4, 2]   swap 5 and 1\n",
    "[1, 4, 5, 2]   swap 5 and 4\n",
    "[1, 4, 2, 5]   swap 5 and 2\n",
    "```\n",
    "\n",
    "This algorithm is called bubble sort because values \"bubble up\" to the top one by one.\n",
    "\n",
    "Our implementation below starts by making a copy of the list so the original one stays unchanged. It also uses a bit of a shorthand notation we have not encountered before, on line 8. The assignment `a, b = b, a` swaps two values, as Python evaluates the right-hand side before assigning either target.\n",
    "\n",
    "**Predict:** Go through the algorithm step by step. When do we reach `break`? Why is it there?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l15-c024",
   "metadata": {},
   "outputs": [],
   "source": [
    "def bubble_sort(values):\n",
    "    result = values.copy()\n",
    "    for pass_number in range(len(result) - 1):\n",
    "        swapped = False\n",
    "        last_unsorted = len(result) - 1 - pass_number\n",
    "        for index in range(last_unsorted):\n",
    "            if result[index] > result[index + 1]:\n",
    "                result[index], result[index + 1] = result[index + 1], result[index]\n",
    "                swapped = True\n",
    "        if not swapped:\n",
    "            break\n",
    "    return result\n",
    "\n",
    "sample = [5, 1, 4, 2, 8]\n",
    "print(bubble_sort(sample))\n",
    "print(sample)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-c025",
   "metadata": {},
   "source": [
    "The `swapped` flag records whether a pass changed anything. We reset it at the start of each pass so that it describes only that pass. If no pair was out of order, the whole list is sorted and we can stop, which we do with `break`.\n",
    "\n",
    "The inner loop stops early enough for `index + 1` to remain a valid index. Its range also gets shorter with each pass, leaving alone the largest items already placed at the end.\n",
    "\n",
    "Trace a few different lists, including empty, one-item, and sorted ones. All return a sorted copy without trying to read beyond the end."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-c026",
   "metadata": {
    "tags": [
     "exercise"
    ]
   },
   "source": [
    "<div class=\"alert alert-success\">\n",
    "<b>Try it yourself: show the passes</b>\n",
    "\n",
    "Let's improve our documentation somewhat. Write `bubble_sort_trace(values)` by adding a print of the list after each complete pass.\n",
    "\n",
    "Try it out on a sorted list, a reverse-sorted list, and a list containing duplicates.\n",
    "</div>\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l15-c027",
   "metadata": {
    "tags": [
     "exercise"
    ]
   },
   "outputs": [],
   "source": [
    "def bubble_sort_trace(values):\n",
    "\tpass\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-c028",
   "metadata": {
    "tags": [
     "solution"
    ]
   },
   "source": [
    "<details>\n",
    "<summary><b>Click for a possible solution</b></summary>\n",
    "\n",
    "```python\n",
    "def bubble_sort_trace(values):\n",
    "    result = values.copy()\n",
    "    for pass_number in range(len(result) - 1):\n",
    "        swapped = False\n",
    "        for index in range(len(result) - 1 - pass_number):\n",
    "            if result[index] > result[index + 1]:\n",
    "                result[index], result[index + 1] = result[index + 1], result[index]\n",
    "                swapped = True\n",
    "        print(result)\n",
    "        if not swapped:\n",
    "            break\n",
    "    return result\n",
    "\n",
    "bubble_sort_trace([4, 3, 2, 1])\n",
    "```\n",
    "</details>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-c029",
   "metadata": {},
   "source": [
    "### Insertion sort\n",
    "\n",
    "Bubble sort is not the only way of sorting lists, however. Say you're playing a game of cards and you want to keep your hand in order. When you pick up a new card, you probalby move the larger cards along to make space for it. **Insertion sort** does the same with a list.\n",
    "\n",
    "We can think of the first item in the list as a list of length one that is already sorted. At each step, we save the next value, moving larger values in the sorted section one position right, and then put the saved value in the gap. The sorted section has now grown by one item, and so on, and so forth.\n",
    "\n",
    "For example, for `[5, 2, 4]`, inserting 2 gives `[2, 5, 4]`. Then inserting 4 gives `[2, 4, 5]`.\n",
    "\n",
    "**Predict:** Insertion sort can be a little more difficult to intuit than bubble sort. Can you trace the following sorting on paper?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l15-c030",
   "metadata": {},
   "outputs": [],
   "source": [
    "def insertion_sort(values):\n",
    "    result = values.copy()\n",
    "    for index in range(1, len(result)):\n",
    "        value_to_insert = result[index]\n",
    "        position = index\n",
    "        while position > 0 and result[position - 1] > value_to_insert:\n",
    "            result[position] = result[position - 1]\n",
    "            position -= 1\n",
    "        result[position] = value_to_insert\n",
    "    return result\n",
    "\n",
    "sample = [5, 2, 4, 6, 1, 3]\n",
    "print(insertion_sort(sample))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-c031",
   "metadata": {},
   "source": [
    "### Algorithm time complexity\n",
    "\n",
    "Why do we bother with these manual implementations? Isn't the built-in Python functionality good enough?\n",
    "\n",
    "Absolutely, and you would rarely write your own sorting function. The point is not that you learn these by heart, but that you get an intuition for how algorithms are designed and how efficient they are.\n",
    "\n",
    "Let's start with search. For a list of 1,024 items, a linear search might inspect all 1,024. But binary search needs at most 11 middle-item checks, since each unsuccessful check discards roughly half of what remains. That's a saving of 1,013 steps! On the other hand, getting the data into sorted order takes work too, and sorting just to perform one search may cost more than a linear search. Sorting once for many searches might be useful, though.\n",
    "\n",
    "For sorting, we can count both comparisons between values and as well as movements of values as steps in the algorithm. Input order matters: insertion sort makes one comparison for each later item of an already sorted list, but on a reverse-sorted list each insertion must move every earlier item. For length `n`, that is `1 + 2 + ... + (n - 1)` moves. This means that the *time complexity* of the algorithm is *quadratic*: doubling a large `n` gives roughly four times as many moves in that case. The time complexity of bubble sort is quadratic too, for the same reason.\n",
    "\n",
    "Below, we have recreated the insertion sort algorithm from above, but this time we are keeping count of the value comparisons as well as the rightward shifts.\n",
    "\n",
    "**Predict:** For five items, which of the two arrangements has more comparisons? How many shifts does the already sorted list need?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l15-c032",
   "metadata": {},
   "outputs": [],
   "source": [
    "def insertion_sort_with_counts(values):\n",
    "    result = values.copy()\n",
    "    comparisons = 0\n",
    "    moves = 0\n",
    "    for index in range(1, len(result)):\n",
    "        value_to_insert = result[index]\n",
    "        position = index\n",
    "        while position > 0:\n",
    "            comparisons += 1\n",
    "            if result[position - 1] <= value_to_insert:\n",
    "                break\n",
    "            result[position] = result[position - 1]\n",
    "            moves += 1\n",
    "            position -= 1\n",
    "        result[position] = value_to_insert\n",
    "    return result, comparisons, moves\n",
    "\n",
    "for sample in [[1, 2, 3, 4, 5], [5, 4, 3, 2, 1]]:\n",
    "    ordered, comparisons, moves = insertion_sort_with_counts(sample)\n",
    "    print(sample, comparisons, moves)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-c033",
   "metadata": {
    "tags": [
     "exercise"
    ]
   },
   "source": [
    "<div class=\"alert alert-success\">\n",
    "<b>Try it yourself: compare the data</b>\n",
    "\n",
    "Run `insertion_sort_with_counts()` on the three lists below. They have the same length but different arrangements. Record comparisons and shifts, and explain the differences. \n",
    "\n",
    "Then, repeat this with sorted and reverse-sorted lists of length 12. Does doubling the length double the reverse-order shifts?\n",
    "</div>\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l15-c034",
   "metadata": {
    "tags": [
     "exercise"
    ]
   },
   "outputs": [],
   "source": [
    "samples = [\n",
    "    [1, 2, 3, 4, 5, 6],\n",
    "    [1, 2, 3, 5, 4, 6],\n",
    "    [6, 5, 4, 3, 2, 1],\n",
    "]\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-c035",
   "metadata": {
    "tags": [
     "solution"
    ]
   },
   "source": [
    "<details><summary><b>Click for a possible solution</b></summary>\n",
    "\n",
    "```python\n",
    "samples = [\n",
    "    [1, 2, 3, 4, 5, 6],\n",
    "    [1, 2, 3, 5, 4, 6],\n",
    "    [6, 5, 4, 3, 2, 1],\n",
    "]\n",
    "for sample in samples:\n",
    "    ordered, comparisons, shifts = insertion_sort_with_counts(sample)\n",
    "    print(sample, comparisons, shifts)\n",
    "# Sorted data stops each inner search immediately, giving 5 comparisons and 0 shifts.\n",
    "# One reversed pair needs 1 shift, so reverse order needs 15 shifts.\n",
    "\n",
    "for sample in [list(range(1, 13)), list(range(12, 0, -1))]:\n",
    "    ordered, comparisons, shifts = insertion_sort_with_counts(sample)\n",
    "    print(comparisons, shifts)\n",
    "# Reverse order needs 66 shifts at length 12, roughly four times as much than length 6.\n",
    "```\n",
    "</details>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-consolidation-prompt",
   "metadata": {
    "tags": [
     "exercise"
    ]
   },
   "source": [
    "## Consolidation challenge\n",
    "\n",
    "Let's bring some of the different ideas from this lecture together into one final challenge.\n",
    "\n",
    "<div class=\"alert alert-success\">\n",
    "<b>Try it yourself: find a course</b>\n",
    "\n",
    "The records below have unique course codes. First, sort them by code using a named key function.\n",
    "\n",
    "Then, write `find_record(sorted_records, target_code)` using binary search, comparing each candidate's `\"code\"` value with the target. Return the whole matching dictionary, or `None` if the code is missing.\n",
    "\n",
    "Test the first, middle, and last codes in sorted order; a missing code; and an empty list.\n",
    "\n",
    "Finally, have a think about efficienty. In this case, would you prefer binary search or linear search?\n",
    "</div>\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "l15-consolidation-work",
   "metadata": {
    "tags": [
     "exercise"
    ]
   },
   "outputs": [],
   "source": [
    "records = [\n",
    "    {\"code\": \"CriSP\", \"room\": \"1.03\"},\n",
    "    {\"code\": \"IP\", \"room\": \"G.07\"},\n",
    "    {\"code\": \"CAFI\", \"room\": \"2.12\"},\n",
    "]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-consolidation-solution",
   "metadata": {
    "tags": [
     "solution"
    ]
   },
   "source": [
    "<details><summary><b>Click for a possible solution</b></summary>\n",
    "\n",
    "For a single search in an unsorted list, a linear search avoids the work of sorting. However, if we keep the records in order and search many times, binary search will use fewer comparisons per search.\n",
    "\n",
    "```python\n",
    "records = [\n",
    "    {\"code\": \"CriSP\", \"room\": \"1.03\"},\n",
    "    {\"code\": \"IP\", \"room\": \"G.07\"},\n",
    "    {\"code\": \"CAFI\", \"room\": \"2.12\"},\n",
    "]\n",
    "\n",
    "def code_of(record):\n",
    "    return record[\"code\"]\n",
    "\n",
    "def find_record(sorted_records, target_code):\n",
    "    low = 0\n",
    "    high = len(sorted_records) - 1\n",
    "    while low <= high:\n",
    "        middle = (low + high) // 2\n",
    "        candidate = sorted_records[middle]\n",
    "        if candidate[\"code\"] == target_code:\n",
    "            return candidate\n",
    "        if candidate[\"code\"] < target_code:\n",
    "            low = middle + 1\n",
    "        else:\n",
    "            high = middle - 1\n",
    "    return None\n",
    "\n",
    "ordered = sorted(records, key=code_of)\n",
    "assert find_record(ordered, \"CAFI\")[\"room\"] == \"2.12\"\n",
    "assert find_record(ordered, \"IP\")[\"room\"] == \"G.07\"\n",
    "assert find_record(ordered, \"CriSP\")[\"room\"] == \"1.03\"\n",
    "assert find_record(ordered, \"FC\") is None\n",
    "assert find_record([], \"IP\") is None\n",
    "```\n",
    "</details>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "l15-consolidation-summary",
   "metadata": {
    "tags": [
     "summary"
    ]
   },
   "source": [
    "## Summary\n",
    "\n",
    "Well done! That concludes our last deep dive into collections in Python. You now have a deeper understanding of how copying, searching, and sorting collections all work, as well as seen the basics of algorithmic efficiency.\n",
    "\n",
    "### Key terms\n",
    "\n",
    "<dl>\n",
    "\t<dt><b>Alias</b></dt>\n",
    "\t<dd>Another name or reference to the same object.</dd>\n",
    "\t<dt><b>Equality</b></dt>\n",
    "\t<dd>Whether two names refer to the same values, tested with <code>==</code>.</dd>\n",
    "\t<dt><b>Identity</b></dt>\n",
    "\t<dd>Whether two names refer to the very same object in memory, tested with <code>is</code>.</dd>\n",
    "\t<dt><b>Shallow copy</b></dt>\n",
    "\t<dd>A new outer collection that shares its contained objects with the original.</dd>\n",
    "\t<dt><b>Deep copy</b></dt>\n",
    "\t<dd>A collection copy that also copies nested mutable objects.</dd>\n",
    "\t<dt><b>Linear search</b></dt>\n",
    "\t<dd>Inspecting items in sequence until a match is found or the collection ends.</dd>\n",
    "\t<dt><b>Binary search</b></dt>\n",
    "\t<dd>Searching a sorted sequence by repeatedly discarding half of the remaining region.</dd>\n",
    "\t<dt><b>Stable sort</b></dt>\n",
    "\t<dd>A sort that preserves the relative input order of items with equal keys.</dd>\n",
    "\t<dt><b>Bubble sort</b></dt>\n",
    "\t<dd>Repeatedly comparing and swapping neighbouring items, placing the largest remaining item at the end of each pass.</dd>\n",
    "\t<dt><b>Insertion sort</b></dt>\n",
    "\t<dd>Growing a sorted section by moving earlier values to make room for the next item.</dd>\n",
    "\t<dt><b>Algorithm time complexity</b></dt>\n",
    "\t<dd>How the time an algorithm needs changes with its input.</dd>\n",
    "</dl>\n",
    "\n",
    "### New syntax\n",
    "\n",
    "<dl>\n",
    "\t<dt><code>a is b</code>, <code>a is not b</code></dt>\n",
    "\t<dd>Tests whether two references identify the same or objects.</dd>\n",
    "\t<dt><code>copy.deepcopy(collection)</code></dt>\n",
    "\t<dd>Copies <code>collection</code> and its nested mutable objects, after importing <code>copy</code>.</dd>\n",
    "\t<dt><code>items.index(value)</code></dt>\n",
    "\t<dd>Finds the first matching item's index in a list; raises <code>ValueError</code> if absent.</dd>\n",
    "\t<dt><code>sorted(items)</code>, <code>list.sort()</code></dt>\n",
    "\t<dd>Creates a sorted collection, and sorts an existing list in place, respectively. The latter returns <code>None</code>.</dd>\n",
    "\t<dt><code>sorted(records, key=key_function)</code></dt>\n",
    "\t<dd>Sorts <code>records</code> using <code>key_function</code> to determine which part of each record to use as the key.</dd>\n",
    "\t<dt><code>left, right = right, left</code></dt>\n",
    "\t<dd>Uses unpacking assignment to swap two values after evaluating the right-hand side.</dd>\n",
    "</dl>\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "pygments_lexer": "ipython3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
