From e0b8a991933a6a983e69393e03b5a026515d8ac4 Mon Sep 17 00:00:00 2001 From: Louis Oliphant <ltoliphant@wisc.edu> Date: Sun, 27 Oct 2024 22:43:19 -0500 Subject: [PATCH] Finished Lec 23 --- .../Lec_23_Function_References.ipynb | 264 ++++++++ ...Lec_23_Function_References_Solution.ipynb} | 578 ++++++++++-------- 2 files changed, 572 insertions(+), 270 deletions(-) rename f24/Louis_Lecture_Notes/23_Function_References/{Lec_23_Function_References_Solution_Oliphant.ipynb => Lec_23_Function_References_Solution.ipynb} (90%) diff --git a/f24/Louis_Lecture_Notes/23_Function_References/Lec_23_Function_References.ipynb b/f24/Louis_Lecture_Notes/23_Function_References/Lec_23_Function_References.ipynb index 52fdc1c..8949d1b 100644 --- a/f24/Louis_Lecture_Notes/23_Function_References/Lec_23_Function_References.ipynb +++ b/f24/Louis_Lecture_Notes/23_Function_References/Lec_23_Function_References.ipynb @@ -45,6 +45,7 @@ }, { "cell_type": "code", +<<<<<<< HEAD "execution_count": 1, "metadata": {}, "outputs": [ @@ -59,6 +60,11 @@ "output_type": "execute_result" } ], +======= + "execution_count": null, + "metadata": {}, + "outputs": [], +>>>>>>> f9e9c99 (finished lec 23 function references) "source": [ "# Warmup 2: Trace Recursion by hand .... possible exam question\n", "\n", @@ -85,11 +91,19 @@ "\n", "- [Python for Everybody, 10.8](https://runestone.academy/ns/books/published/py4e-int/dictionaries/toctree.html)\n", "\n", +<<<<<<< HEAD "As we have learned previously, all variables in Python refer to objects.\n", "\n", "This is also true for functions -- their name refers to a function object, and it gives us more power as programmers.\n", "\n", "## Learning Objectives\n", +======= + "As we have learned previously, all variables contain references to objects.\n", + "\n", + "This is also true for function names, and it gives us more power as programmers.\n", + "\n", + "**Learning Objectives:**\n", +>>>>>>> f9e9c99 (finished lec 23 function references) "\n", "- Define a function reference and trace code that uses function references.\n", "- Explain the default use of sorted() on lists of tuples, and dictionaries.\n", @@ -98,6 +112,7 @@ ] }, { +<<<<<<< HEAD "cell_type": "markdown", "metadata": {}, "source": [ @@ -137,6 +152,8 @@ ] }, { +======= +>>>>>>> f9e9c99 (finished lec 23 function references) "cell_type": "code", "execution_count": null, "metadata": {}, @@ -146,6 +163,7 @@ "# try this in Python Tutor\n", "\n", "x = [1,2,3]\n", +<<<<<<< HEAD "y = x\n", "\n", "def f(some_list): # what is f? \n", @@ -156,6 +174,22 @@ "g = f # what is g?\n", "\n", "# TODO: Try calling the function using the variable g\n" +======= + "y = x # y holds a reference to the same object as x\n", + "\n", + "def f(some_list): # f is the name of the function\n", + " return some_list[-1]\n", + "\n", + "z = f(y) # z stores the result of a call to f\n", + "\n", + "g = f # g holds a reference to the same function as f\n", + "\n", + "# TODO: similar to calling f() and storing the result in z, but now call g and store the results in z2\n", + "\n", + "\n", + "print(z)\n", + "print(z2)" +>>>>>>> f9e9c99 (finished lec 23 function references) ] }, { @@ -181,12 +215,17 @@ "cell_type": "markdown", "metadata": {}, "source": [ +<<<<<<< HEAD "## Functions can be passed as arguments!\n", "Take a look at the code below. Watch it run using [PythonTutor](https://pythontutor.com/render.html#code=def%20hammer%28%29%3A%0A%20%20%20%20print%28%22tap%20tap%20tap%22%29%0A%0Adef%20call_n_times%28f,%20n%29%3A%0A%20%20%20%20for%20i%20in%20range%28n%29%3A%0A%20%20%20%20%20%20%20%20f%28%29%0A%0Acall_n_times%28hammer,%203%29&cumulative=false&curInstr=0&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false). Then modify the code to finish the `screwdriver()` function and write a line of code to call `call_n_times()` passing in as arguments your `screwdriver` function and the value 5." +======= + "[PythonTutor Link](https://pythontutor.com/visualize.html#code=def%20hammer%28%29%3A%0A%20%20%20%20print%28%22tap%20tap%20tap%22%29%0A%20%20%20%20%0Adef%20call_n_times%28f,%20n%29%3A%0A%20%20%20%20for%20i%20in%20range%28n%29%3A%0A%20%20%20%20%20%20%20%20f%28%29%0A%0Acall_n_times%28hammer,%203%29&cumulative=false&curInstr=0&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false)" +>>>>>>> f9e9c99 (finished lec 23 function references) ] }, { "cell_type": "code", +<<<<<<< HEAD "execution_count": 2, "metadata": {}, "outputs": [ @@ -202,6 +241,13 @@ ], "source": [ "# function references can be passed as arguments ...Wow!\n", +======= + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# function references can be passed as arguments ... Wow!\n", +>>>>>>> f9e9c99 (finished lec 23 function references) "\n", "# first: try this in Python Tutor\n", "\n", @@ -291,7 +337,15 @@ "source": [ "We already did the math behind `manhattan_distance` and `euclidean_distance` for you!\n", "\n", +<<<<<<< HEAD "**Hint:** `distance_algo` should be a reference to a function that calculates distance between two points.\n", +======= + "Finish writing the `calculate_distances()` function, which should go over every point in `left_point`\n", + "and print the point, the matching point in `right_point` and the distance between them.\n", + "\n", + "**Hint:** The `distance_algo` parameter should be a reference to a function that calculates the distance between two points.\n", + "\n", +>>>>>>> f9e9c99 (finished lec 23 function references) "\n", "Then, call calculate_distances measuring first in manhattan_distance, then euclidean_distance." ] @@ -326,7 +380,18 @@ "cell_type": "markdown", "metadata": {}, "source": [ +<<<<<<< HEAD "### Explain the default use of sorted() on lists of tuples, and on dictionaries.\n" +======= + "### Explain the default use of sorted() on lists of tuples, and on dictionaries.\n", + "\n", + "The `sort()` method and the `sorted()` function have two optional arguments, `key` and `reverse`. These\n", + "arguments control how the list will be sorted. The `reverse` argument defaults to `False`, but if you set\n", + "it to true then the list will be sorted in reverse order.\n", + "\n", + "Take a look at the help function for `sorted()` in the cell below then try sorting the `populations` \n", + "list, first in sorted order then in reverse sorted order." +>>>>>>> f9e9c99 (finished lec 23 function references) ] }, { @@ -335,14 +400,20 @@ "metadata": {}, "outputs": [], "source": [ +<<<<<<< HEAD "# first... did you know that sort/sorted takes a 2nd argument called reverse?\n", "\n", "populations = [55, 77, 33, 99, 22]\n", "# TODO: sort populations in reverse" +======= + "# print out the help for the sorted function and read about the reverse and key parameters\n", + "help(sorted)" +>>>>>>> f9e9c99 (finished lec 23 function references) ] }, { "cell_type": "code", +<<<<<<< HEAD "execution_count": 1, "metadata": {}, "outputs": [ @@ -362,6 +433,40 @@ "output_type": "execute_result" } ], +======= + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "populations = [55, 77, 33, 99, 22]\n", + "# TODO: sort populations then sort again in reverse order" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## The `key` parameter in `sort()` and `sorted()`\n", + "\n", + "The `key` parameter is a function that can be used to customize how the list will be sorted.\n", + "This is especially useful when sorting things where it is not clear what their order should be or if you\n", + "want to change the default soriting behavior. The function that should be passed to `key` takes as input\n", + "one item at a time from the list and it should return something that the `sort()` or `sorted()`\n", + "function does know how to sort, like a string or a number.\n", + "\n", + "For example, take a look at the `owhockey_badgers` list below. Notice that the list contains tuples.\n", + "If you were to call `sort()` or `sorted()` on this list, the default behavior would be to sort using the first\n", + "item in each tuple, then the second, and so on.\n", + "\n", + "Run the code in the cell below to see the default sorting behavior." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], +>>>>>>> f9e9c99 (finished lec 23 function references) "source": [ "# Sorting part 1....how are lists of tuples sorted?\n", "# olympic womens hockey badgers...first, last, age\n", @@ -371,7 +476,12 @@ " (\"Amanda\", \"Kessel\", 30),\n", " (\"Alex\", \"Cavalenni\", 30), \n", " (\"Caroline\", \"Harvey\", 19),\n", +<<<<<<< HEAD " (\"Abbey\", \"Roque\", 24)\n", +======= + " (\"Abbey\", \"Roquet\", 24),\n", + " (\"Abbey\", \"Roques\", 27)\n", +>>>>>>> f9e9c99 (finished lec 23 function references) " ]\n", "\n", "\n", @@ -381,6 +491,20 @@ ] }, { +<<<<<<< HEAD +======= + "cell_type": "markdown", + "metadata": {}, + "source": [ + "If you want to have the list sorted by the age of each player, then you need to tell\n", + "the sorting algorithm which item to sort by. You can create a function that takes\n", + "as input a single item from the list and returns the value that you want to be used\n", + "when sorting. In the cell below three such functions are created to return the\n", + "item from the tuple that you want to use when sorting the list." + ] + }, + { +>>>>>>> f9e9c99 (finished lec 23 function references) "cell_type": "code", "execution_count": null, "metadata": {}, @@ -396,7 +520,20 @@ "def select2(some_tuple):\n", " return some_tuple[2]\n", "\n", +<<<<<<< HEAD "# Test these functions on the tuple (\"Mike\", \"Gurmail\", \"Cole\")\n" +======= + "# TODO: Test these functions on the tuple (\"Mike\", \"Louis\", \"Cole\")\n", + "test_tuple = (\"Mike\", \"Louis\", \"Cole\")\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Try using each of these select functions as the key when sorting the `owhockey_badgers` list." +>>>>>>> f9e9c99 (finished lec 23 function references) ] }, { @@ -408,6 +545,7 @@ "# call sorted using the 'key' argument \n", "# sort and sorted can take a parameter named key\n", "# key is a reference to a function!\n", +<<<<<<< HEAD "sorted(owhockey_badgers, key=select2)" ] }, @@ -427,12 +565,18 @@ "outputs": [], "source": [ "# sort the list of tuples based on the age\n" +======= + "# TODO: Try sorting by first name, last name, and age\n", + "\n", + "sorted(owhockey_badgers, key=...)" +>>>>>>> f9e9c99 (finished lec 23 function references) ] }, { "cell_type": "markdown", "metadata": {}, "source": [ +<<<<<<< HEAD "### Using `lambda`\n", "- `lambda` functions are a way to abstract a function reference\n", "- lambdas are simple functions with:\n", @@ -446,6 +590,13 @@ "```python \n", "lambda parameters: expression\n", "```" +======= + "The default behavior when sorting a list of dictionaries, is to fail. Python does not\n", + "know how to sort dictionaries. In this case you must have a `key` function that can extract\n", + "the right value so Python will know how to sort. Try sorting without passing a key function\n", + "to sort the list of dictionaries then write a function to get the `age` key from the dictionary\n", + "and use that when sorting." +>>>>>>> f9e9c99 (finished lec 23 function references) ] }, { @@ -454,6 +605,7 @@ "metadata": {}, "outputs": [], "source": [ +<<<<<<< HEAD "# sorting part 3....using lambdas\n", "\n", "'''\n", @@ -464,12 +616,96 @@ "sorted(owhockey_badgers, key = lambda each_tuple : each_tuple[-1])\n", "\n", "# read the lambda as: my no-name function has each_tuple as a parameter\n", +======= + "people = [\n", + " {'first':'Louis', 'last':'Oliphant', 'age':53},\n", + " {'first':'Becky', 'last':'Brown', 'age':52},\n", + " {'first':'Sam', 'last':'Luna-Nelson', 'age':26},\n", + " {'first':'Sally', 'last':'Fields', 'age':47}\n", + "]\n", + "\n", + "##TODO: first try sorting without passing a function for the key parameter\n", + "\n", + "sorted(people)\n", + " " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "\n", + "##TODO: finish the get_age() function that takes a single dictionary and returns\n", + "## the age key from the dictionary.\n", + "\n", + "def get_age(d):\n", + " #return the 'age' key\n", + " pass\n", + "\n", + "##TODO: use the get_age function as the key and try sorting again\n", + "\n", + "sorted(people, key=...)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Using `lambda` functions\n", + "- `lambda` functions are a way to abstract a function reference\n", + "- lambdas are simple functions with:\n", + " - multiple possible parameters\n", + " - single **expression** line as the function body\n", + "- lambdas are useful abstractions for:\n", + " - mathematical functions\n", + " - lookup operations\n", + "- lambdas are often associated with a collection of values within a list\n", + "- Syntax:\n", + " \n", + "```python \n", + "lambda parameters: expression\n", + "```\n", + "\n", + "Here are some examples of creating a function using this lambda notation. Note that the variable holds the *function*. Below each creation of the function is a call to the function.\n", + "\n", + "```python\n", + "f = lambda a : a + 10\n", + "print(f(1))\n", + "```\n", + "```\n", + "11\n", + "```\n", + "```python\n", + "f2 = lambda a, b : a * b\n", + "print(f2(3,4))\n", + "```\n", + "```\n", + "12\n", + "```\n", + "\n", + "Let's use a lambda function to sort the `owhockey_badgers` tuple by the age (i.e. the last field)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "\n", + "sorted(owhockey_badgers, key = lambda each_tuple : each_tuple[-1])\n", + "\n", + "# read the lambda as: my no-name function has each_tuple from owhockey_badgers as a parameter\n", +>>>>>>> f9e9c99 (finished lec 23 function references) "# and returns each_tuple[-1] (the last element)\n", "# the variable 'each_tuple' is like a function parameter" ] }, { "cell_type": "code", +<<<<<<< HEAD "execution_count": 5, "metadata": {}, "outputs": [ @@ -490,6 +726,15 @@ "def no_name(x):\n", " return len(x[0])\n", "'''" +======= + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# TODO: sort the people list of dictionaries by the last name\n", + "\n", + "sorted(people, key = ...)" +>>>>>>> f9e9c99 (finished lec 23 function references) ] }, { @@ -498,13 +743,20 @@ "metadata": {}, "outputs": [], "source": [ +<<<<<<< HEAD "# TODO: Sort the list by the length of their full name\n" +======= + "# TODO: Sort the people list of dictionaries by the LENGTH of their last name\n", + "\n", + "sorted(people, key = ...)\n" +>>>>>>> f9e9c99 (finished lec 23 function references) ] }, { "cell_type": "markdown", "metadata": {}, "source": [ +<<<<<<< HEAD "### OK, I can sort a list of tuples....what about a list of dictionaries?" ] }, @@ -562,6 +814,11 @@ "metadata": {}, "source": [ "### This is all great, but what I'd really like to do is to sort dictionaries!\n" +======= + "### This is all great, but what I'd really like to do is to sort dictionaries!\n", + "\n", + "From Python 3.7 onwards, the standard dict type maintains insertion order by default ([see here](https://mail.python.org/pipermail/python-dev/2017-December/151283.html)), so a dictionary could be ordered, but what happens if you try and sort a dictionary?" +>>>>>>> f9e9c99 (finished lec 23 function references) ] }, { @@ -602,7 +859,11 @@ "\n", "# let's sort menu.items() the same way we sorted a list of tuples\n", "\n", +<<<<<<< HEAD "sorted(menu.items(), key = lambda t : t[0] ) # set the sorting key to a lambda expressoin" +======= + "sorted(menu.items(), key = lambda t : t[0] ) # set the sorting key to a lambda expression" +>>>>>>> f9e9c99 (finished lec 23 function references) ] }, { @@ -625,6 +886,7 @@ ] }, { +<<<<<<< HEAD "cell_type": "code", "execution_count": null, "metadata": {}, @@ -634,6 +896,8 @@ ] }, { +======= +>>>>>>> f9e9c99 (finished lec 23 function references) "cell_type": "markdown", "metadata": {}, "source": [ diff --git a/f24/Louis_Lecture_Notes/23_Function_References/Lec_23_Function_References_Solution_Oliphant.ipynb b/f24/Louis_Lecture_Notes/23_Function_References/Lec_23_Function_References_Solution.ipynb similarity index 90% rename from f24/Louis_Lecture_Notes/23_Function_References/Lec_23_Function_References_Solution_Oliphant.ipynb rename to f24/Louis_Lecture_Notes/23_Function_References/Lec_23_Function_References_Solution.ipynb index 7c5ad1d..c4c97c8 100644 --- a/f24/Louis_Lecture_Notes/23_Function_References/Lec_23_Function_References_Solution_Oliphant.ipynb +++ b/f24/Louis_Lecture_Notes/23_Function_References/Lec_23_Function_References_Solution.ipynb @@ -1,5 +1,12 @@ { "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Warmup" + ] + }, { "cell_type": "code", "execution_count": 1, @@ -67,7 +74,7 @@ }, { "cell_type": "code", - "execution_count": 2, + "execution_count": 3, "metadata": {}, "outputs": [ { @@ -76,7 +83,7 @@ "16807" ] }, - "execution_count": 2, + "execution_count": 3, "metadata": {}, "output_type": "execute_result" } @@ -87,7 +94,7 @@ "def mystery(a, b): \n", "# precondition: assume a > 0 and b > 0\n", " if b == 1: \n", - " return a;\n", + " return a\n", " return a * mystery( a, b - 1 )\n", "\n", "# make a function call here\n", @@ -95,18 +102,23 @@ "\n", "#Q: What would be the result if we call\n", "#. mystery(-3, -1) ??\n", - "# If b starts at -1, and we subtract 1 each time we call a mystery, it will never == 1\n" + "# If b starts at -1, and we subtract 1 each time we call a mystery,\n", + "# it will never == 1\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "## Lecture 23: Functions are Objects!\n", + "# Functions are Objects!\n", + "\n", + "## Reading\n", "\n", - "As we have learned previously, all variables in Python are stored as objects.\n", + "- [Python for Everybody, 10.8](https://runestone.academy/ns/books/published/py4e-int/dictionaries/toctree.html)\n", "\n", - "This is also true for functions, and it gives us more power as programmers.\n", + "As we have learned previously, all variables contain references to objects.\n", + "\n", + "This is also true for function names, and it gives us more power as programmers.\n", "\n", "**Learning Objectives:**\n", "\n", @@ -118,18 +130,16 @@ }, { "cell_type": "code", - "execution_count": 3, + "execution_count": 4, "metadata": {}, "outputs": [ { - "data": { - "text/plain": [ - "3" - ] - }, - "execution_count": 3, - "metadata": {}, - "output_type": "execute_result" + "name": "stdout", + "output_type": "stream", + "text": [ + "3\n", + "3\n" + ] } ], "source": [ @@ -137,19 +147,20 @@ "# try this in Python Tutor\n", "\n", "x = [1,2,3]\n", - "y = x\n", + "y = x # y holds a reference to the same object as x\n", "\n", - "def f(some_list): # what is f? its a function but also an object\n", + "def f(some_list): # f is the name of the function\n", " return some_list[-1]\n", "\n", - "z = f(y) # z stores the result of a call to f\n", + "z = f(y) # z stores the result of a call to f\n", "\n", - "g = f # what is g? it is a reference to an object that is a function\n", + "g = f # g holds a reference to the same function as f\n", "\n", - "# TODO: similar to line 10, store the result of a call to g\n", + "# TODO: similar to calling f() and storing the result in z, but now call g and store the results in z2\n", + "z2 = g(y)\n", "\n", - "w = g(x) # calls the same function\n", - "w" + "print(z)\n", + "print(z2)" ] }, { @@ -180,7 +191,7 @@ }, { "cell_type": "code", - "execution_count": 4, + "execution_count": 5, "metadata": {}, "outputs": [ { @@ -190,16 +201,16 @@ "tap tap tap\n", "tap tap tap\n", "tap tap tap\n", - "churn churn churn\n", - "churn churn churn\n", - "churn churn churn\n", - "churn churn churn\n", - "churn churn churn\n" + "turn turn turn\n", + "turn turn turn\n", + "turn turn turn\n", + "turn turn turn\n", + "turn turn turn\n" ] } ], "source": [ - "# function references can be passed as arguments ...Wow!\n", + "# function references can be passed as arguments ... Wow!\n", "\n", "# first: try this in Python Tutor\n", "\n", @@ -209,7 +220,7 @@ "# then on your own: define a function called screwdriver\n", "\n", "def screwdriver():\n", - " print(\"churn churn churn\")\n", + " print(\"turn turn turn\")\n", "\n", "def call_n_times(f, n):\n", " for i in range(n):\n", @@ -218,8 +229,7 @@ "call_n_times(hammer, 3)\n", "\n", "# then on your own: invoke call_n_times with screwdriver and 5 as arguments\n", - "\n", - "call_n_times(screwdriver, 5)\n" + "call_n_times(screwdriver,5)" ] }, { @@ -250,12 +260,12 @@ "source": [ "### Review: NamedTuples\n", "\n", - "We create a namedtuple `Point` with named attributes `x` and `y`. We then create lists of points we want to calculate distances between" + "We create a namedtuple `Point` with named attributes `x` and `y`. We then create lists of points we want to calculate distances between." ] }, { "cell_type": "code", - "execution_count": 5, + "execution_count": 6, "metadata": {}, "outputs": [], "source": [ @@ -266,13 +276,17 @@ "left_points = [\n", " Point(0, 0),\n", " Point(3, 3),\n", - " Point(2, 2)\n", + " Point(2, 2),\n", + " # TODO: Add another point!\n", + " Point(1, 1)\n", "]\n", "\n", "right_points = [\n", " Point(5, 5),\n", " Point(0, 3),\n", - " Point(2, 2)\n", + " Point(2, 2),\n", + " # TODO: Add another point!\n", + " Point(0, 0)\n", "]" ] }, @@ -289,26 +303,34 @@ "source": [ "We already did the math behind `manhattan_distance` and `euclidean_distance` for you!\n", "\n", - "**Hint:** `distance_algo` should be a reference to a function that calculates distance between two points.\n", + "Finish writing the `calculate_distances()` function, which should go over every point in `left_point`\n", + "and print the point, the matching point in `right_point` and the distance between them.\n", + "\n", + "**Hint:** The `distance_algo` parameter should be a reference to a function that calculates the distance between two points.\n", + "\n", "\n", "Then, call calculate_distances measuring first in manhattan_distance, then euclidean_distance." ] }, { "cell_type": "code", - "execution_count": 6, + "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ - "10\n", - "3\n", - "0\n", - "7.0710678118654755\n", - "3.0\n", - "0.0\n" + "MANHATTAN DISTANCE\n", + "Point(x=0, y=0) Point(x=5, y=5) 10\n", + "Point(x=3, y=3) Point(x=0, y=3) 3\n", + "Point(x=2, y=2) Point(x=2, y=2) 0\n", + "Point(x=1, y=1) Point(x=0, y=0) 2\n", + "EUCLIDEAN DISTANCE\n", + "Point(x=0, y=0) Point(x=5, y=5) 7.0710678118654755\n", + "Point(x=3, y=3) Point(x=0, y=3) 3.0\n", + "Point(x=2, y=2) Point(x=2, y=2) 0.0\n", + "Point(x=1, y=1) Point(x=0, y=0) 1.4142135623730951\n" ] } ], @@ -325,13 +347,18 @@ " dist_y = (point1.y - point2.y) ** 2\n", " return math.sqrt(dist_x + dist_y)\n", "\n", + "# TODO: Complete this function!\n", "def calculate_distances(distance_algo):\n", " for i in range(len(left_points)):\n", " left_point = left_points[i]\n", " right_point = right_points[i]\n", - " print(distance_algo(left_point, right_point))\n", + " print(left_point, right_point, distance_algo(left_point, right_point))\n", "\n", + "# TODO: Calculate the distance between the points using manhattan distance\n", + "# TODO: Calculate the distance between the points using euclidean distance\n", + "print(\"MANHATTAN DISTANCE\")\n", "calculate_distances(manhattan_distance)\n", + "print(\"EUCLIDEAN DISTANCE\")\n", "calculate_distances(euclidean_distance)" ] }, @@ -339,42 +366,91 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "### Explain the default use of sorted() on lists of tuples, and on dictionaries.\n" + "### Explain the default use of sorted() on lists of tuples, and on dictionaries.\n", + "\n", + "The `sort()` method and the `sorted()` function have two optional arguments, `key` and `reverse`. These\n", + "arguments control how the list will be sorted. The `reverse` argument defaults to `False`, but if you set\n", + "it to true then the list will be sorted in reverse order.\n", + "\n", + "Take a look at the help function for `sorted()` in the cell below then try sorting the `populations` \n", + "list, first in sorted order then in reverse sorted order." ] }, { "cell_type": "code", - "execution_count": 7, + "execution_count": 11, "metadata": {}, "outputs": [ { - "data": { - "text/plain": [ - "[99, 77, 55, 33, 22]" - ] - }, - "execution_count": 7, - "metadata": {}, - "output_type": "execute_result" + "name": "stdout", + "output_type": "stream", + "text": [ + "Help on built-in function sorted in module builtins:\n", + "\n", + "sorted(iterable, /, *, key=None, reverse=False)\n", + " Return a new list containing all items from the iterable in ascending order.\n", + " \n", + " A custom key function can be supplied to customize the sort order, and the\n", + " reverse flag can be set to request the result in descending order.\n", + "\n" + ] + } + ], + "source": [ + "# print out the help for the sorted function and read about the reverse and key parameters\n", + "help(sorted)" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[22, 33, 55, 77, 99]\n", + "[99, 77, 55, 33, 22]\n" + ] } ], "source": [ - "# first... did you know that sort/sorted takes a 2nd argument called reverse?\n", - "\n", "populations = [55, 77, 33, 99, 22]\n", - "# TODO: sort populations in reverse\n", - "sorted(populations, reverse=True)" + "# TODO: sort populations then sort again in reverse order\n", + "print(sorted(populations))\n", + "print(sorted(populations,reverse=True))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## The `key` parameter in `sort()` and `sorted()`\n", + "\n", + "The `key` parameter is a function that can be used to customize how the list will be sorted.\n", + "This is especially useful when sorting things where it is not clear what their order should be or if you\n", + "want to change the default soriting behavior. The function that should be passed to `key` takes as input\n", + "one item at a time from the list and it should return something that the `sort()` or `sorted()`\n", + "function does know how to sort, like a string or a number.\n", + "\n", + "For example, take a look at the `owhockey_badgers` list below. Notice that the list contains tuples.\n", + "If you were to call `sort()` or `sorted()` on this list, the default behavior would be to sort using the first\n", + "item in each tuple, then the second, and so on.\n", + "\n", + "Run the code in the cell below to see the default sorting behavior." ] }, { "cell_type": "code", - "execution_count": 8, + "execution_count": 13, "metadata": {}, "outputs": [ { "data": { "text/plain": [ - "[('Abbey', 'Roque', 24),\n", + "[('Abbey', 'Roques', 27),\n", + " ('Abbey', 'Roquet', 24),\n", " ('Alex', 'Cavalenni', 30),\n", " ('Amanda', 'Kessel', 30),\n", " ('Brianna', 'Decker', 30),\n", @@ -382,7 +458,7 @@ " ('Hillary', 'Knight', 32)]" ] }, - "execution_count": 8, + "execution_count": 13, "metadata": {}, "output_type": "execute_result" } @@ -396,7 +472,8 @@ " (\"Amanda\", \"Kessel\", 30),\n", " (\"Alex\", \"Cavalenni\", 30), \n", " (\"Caroline\", \"Harvey\", 19),\n", - " (\"Abbey\", \"Roque\", 24)\n", + " (\"Abbey\", \"Roquet\", 24),\n", + " (\"Abbey\", \"Roques\", 27)\n", " ]\n", "\n", "\n", @@ -405,18 +482,29 @@ "# what did this make? How was it sorted? " ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "If you want to have the list sorted by the age of each player, then you need to tell\n", + "the sorting algorithm which item to sort by. You can create a function that takes\n", + "as input a single item from the list and returns the value that you want to be used\n", + "when sorting. In the cell below three such functions are created to return the\n", + "item from the tuple that you want to use when sorting the list." + ] + }, { "cell_type": "code", - "execution_count": 9, + "execution_count": 14, "metadata": {}, "outputs": [ { "data": { "text/plain": [ - "'Gurmail'" + "'Mike'" ] }, - "execution_count": 9, + "execution_count": 14, "metadata": {}, "output_type": "execute_result" } @@ -432,28 +520,37 @@ "def select2(some_tuple):\n", " return some_tuple[2]\n", "\n", - "# Test these functions on the tuple (\"Mike\", \"Gurmail\", \"Cole\")\n", - "my_tuple = (\"Mike\", \"Gurmail\", \"Cole\")\n", - "select1(my_tuple)\n" + "# TODO: Test these functions on the tuple (\"Mike\", \"Louis\", \"Cole\")\n", + "test_tuple = (\"Mike\", \"Louis\", \"Cole\")\n", + "\n", + "select0(test_tuple)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Try using each of these select functions as the key when sorting the `owhockey_badgers` list." ] }, { "cell_type": "code", - "execution_count": 10, + "execution_count": 15, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[('Caroline', 'Harvey', 19),\n", - " ('Abbey', 'Roque', 24),\n", + " ('Abbey', 'Roquet', 24),\n", + " ('Abbey', 'Roques', 27),\n", " ('Brianna', 'Decker', 30),\n", " ('Amanda', 'Kessel', 30),\n", " ('Alex', 'Cavalenni', 30),\n", " ('Hillary', 'Knight', 32)]" ] }, - "execution_count": 10, + "execution_count": 15, "metadata": {}, "output_type": "execute_result" } @@ -462,271 +559,218 @@ "# call sorted using the 'key' argument \n", "# sort and sorted can take a parameter named key\n", "# key is a reference to a function!\n", + "# TODO: Try sorting by first name, last name, and age\n", "\n", "sorted(owhockey_badgers, key=select2)" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The default behavior when sorting a list of dictionaries, is to fail. Python does not\n", + "know how to sort dictionaries. In this case you must have a `key` function that can extract\n", + "the right value so Python will know how to sort. Try sorting without passing a key function\n", + "to sort the list of dictionaries then write a function to get the `age` key from the dictionary\n", + "and use that when sorting." + ] + }, { "cell_type": "code", - "execution_count": 11, + "execution_count": 16, "metadata": {}, "outputs": [ { - "data": { - "text/plain": [ - "[('Alex', 'Cavalenni', 30),\n", - " ('Brianna', 'Decker', 30),\n", - " ('Caroline', 'Harvey', 19),\n", - " ('Amanda', 'Kessel', 30),\n", - " ('Hillary', 'Knight', 32),\n", - " ('Abbey', 'Roque', 24)]" - ] - }, - "execution_count": 11, - "metadata": {}, - "output_type": "execute_result" + "ename": "TypeError", + "evalue": "'<' not supported between instances of 'dict' and 'dict'", + "output_type": "error", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", + "Cell \u001b[0;32mIn[16], line 10\u001b[0m\n\u001b[1;32m 1\u001b[0m people \u001b[38;5;241m=\u001b[39m [\n\u001b[1;32m 2\u001b[0m {\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mfirst\u001b[39m\u001b[38;5;124m'\u001b[39m:\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mLouis\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mlast\u001b[39m\u001b[38;5;124m'\u001b[39m:\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mOliphant\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mage\u001b[39m\u001b[38;5;124m'\u001b[39m:\u001b[38;5;241m53\u001b[39m},\n\u001b[1;32m 3\u001b[0m {\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mfirst\u001b[39m\u001b[38;5;124m'\u001b[39m:\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mBecky\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mlast\u001b[39m\u001b[38;5;124m'\u001b[39m:\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mBrown\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mage\u001b[39m\u001b[38;5;124m'\u001b[39m:\u001b[38;5;241m52\u001b[39m},\n\u001b[1;32m 4\u001b[0m {\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mfirst\u001b[39m\u001b[38;5;124m'\u001b[39m:\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mSam\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mlast\u001b[39m\u001b[38;5;124m'\u001b[39m:\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mLuna-Nelson\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mage\u001b[39m\u001b[38;5;124m'\u001b[39m:\u001b[38;5;241m26\u001b[39m},\n\u001b[1;32m 5\u001b[0m {\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mfirst\u001b[39m\u001b[38;5;124m'\u001b[39m:\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mSally\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mlast\u001b[39m\u001b[38;5;124m'\u001b[39m:\u001b[38;5;124m'\u001b[39m\u001b[38;5;124mFields\u001b[39m\u001b[38;5;124m'\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mage\u001b[39m\u001b[38;5;124m'\u001b[39m:\u001b[38;5;241m47\u001b[39m}\n\u001b[1;32m 6\u001b[0m ]\n\u001b[1;32m 8\u001b[0m \u001b[38;5;66;03m##TODO: first try sorting without passing a function for the key parameter\u001b[39;00m\n\u001b[0;32m---> 10\u001b[0m \u001b[38;5;28;43msorted\u001b[39;49m\u001b[43m(\u001b[49m\u001b[43mpeople\u001b[49m\u001b[43m)\u001b[49m\n", + "\u001b[0;31mTypeError\u001b[0m: '<' not supported between instances of 'dict' and 'dict'" + ] } ], "source": [ - "# sort the list of tuples based on the last name\n", - "sorted(owhockey_badgers, key=select1)" + "people = [\n", + " {'first':'Louis', 'last':'Oliphant', 'age':53},\n", + " {'first':'Becky', 'last':'Brown', 'age':52},\n", + " {'first':'Sam', 'last':'Luna-Nelson', 'age':26},\n", + " {'first':'Sally', 'last':'Fields', 'age':47}\n", + "]\n", + "\n", + "##TODO: first try sorting without passing a function for the key parameter\n", + "\n", + "sorted(people)\n", + " " ] }, { "cell_type": "code", - "execution_count": 12, + "execution_count": 17, "metadata": {}, "outputs": [ { "data": { "text/plain": [ - "[('Caroline', 'Harvey', 19),\n", - " ('Abbey', 'Roque', 24),\n", - " ('Brianna', 'Decker', 30),\n", - " ('Amanda', 'Kessel', 30),\n", - " ('Alex', 'Cavalenni', 30),\n", - " ('Hillary', 'Knight', 32)]" + "[{'first': 'Sam', 'last': 'Luna-Nelson', 'age': 26},\n", + " {'first': 'Sally', 'last': 'Fields', 'age': 47},\n", + " {'first': 'Becky', 'last': 'Brown', 'age': 52},\n", + " {'first': 'Louis', 'last': 'Oliphant', 'age': 53}]" ] }, - "execution_count": 12, + "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ - "# sort the list of tuples based on the age\n", - "sorted(owhockey_badgers, key=select2)" + "\n", + "##TODO: finish the get_age() function that takes a single dictionary and returns\n", + "## the age key from the dictionary.\n", + "\n", + "def get_age(d):\n", + " #return the 'age' key\n", + " return d['age']\n", + "\n", + "##TODO: use the get_age function as the key and try sorting again\n", + "\n", + "sorted(people, key=get_age)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "### Using `lambda`\n", + "### Using `lambda` functions\n", "- `lambda` functions are a way to abstract a function reference\n", "- lambdas are simple functions with:\n", " - multiple possible parameters\n", - " - single expression line as the function body\n", + " - single **expression** line as the function body\n", "- lambdas are useful abstractions for:\n", " - mathematical functions\n", " - lookup operations\n", "- lambdas are often associated with a collection of values within a list\n", - "- Syntax: \n", + "- Syntax:\n", + " \n", "```python \n", "lambda parameters: expression\n", - "```\n" + "```\n", + "\n", + "Here are some examples of creating a function using this lambda notation. Note that the variable holds the *function*. Below each creation of the function is a call to the function.\n", + "\n", + "```python\n", + "f = lambda a : a + 10\n", + "print(f(1))\n", + "```\n", + "```\n", + "11\n", + "```\n", + "```python\n", + "f2 = lambda a, b : a * b\n", + "print(f2(3,4))\n", + "```\n", + "```\n", + "12\n", + "```\n", + "\n", + "Let's use a lambda function to sort the `owhockey_badgers` tuple by the age (i.e. the last field)." ] }, { "cell_type": "code", - "execution_count": 13, + "execution_count": 18, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[('Caroline', 'Harvey', 19),\n", - " ('Abbey', 'Roque', 24),\n", + " ('Abbey', 'Roquet', 24),\n", + " ('Abbey', 'Roques', 27),\n", " ('Brianna', 'Decker', 30),\n", " ('Amanda', 'Kessel', 30),\n", " ('Alex', 'Cavalenni', 30),\n", " ('Hillary', 'Knight', 32)]" ] }, - "execution_count": 13, + "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ - "# sorting part 3....using lambdas\n", - "\n", - "'''\n", - "def no_name(each_tuple):\n", - " return each_tuple[-1]\n", - "'''\n", "\n", "sorted(owhockey_badgers, key = lambda each_tuple : each_tuple[-1])\n", "\n", - "# read the lambda as: my no-name function has each_tuple as a parameter\n", + "# read the lambda as: my no-name function has each_tuple from owhockey_badgers as a parameter\n", "# and returns each_tuple[-1] (the last element)\n", "# the variable 'each_tuple' is like a function parameter" ] }, { "cell_type": "code", - "execution_count": 14, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "[('Alex', 'Cavalenni', 30),\n", - " ('Abbey', 'Roque', 24),\n", - " ('Amanda', 'Kessel', 30),\n", - " ('Hillary', 'Knight', 32),\n", - " ('Brianna', 'Decker', 30),\n", - " ('Caroline', 'Harvey', 19)]" - ] - }, - "execution_count": 14, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# TODO: sort the list by the length of the first name\n", - "'''\n", - "def no_name(x):\n", - " return len(x[0])\n", - "'''\n", - "sorted(owhockey_badgers, key = lambda x : len(x[0]))" - ] - }, - { - "cell_type": "code", - "execution_count": 15, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "[('Abbey', 'Roque', 24),\n", - " ('Amanda', 'Kessel', 30),\n", - " ('Hillary', 'Knight', 32),\n", - " ('Brianna', 'Decker', 30),\n", - " ('Alex', 'Cavalenni', 30),\n", - " ('Caroline', 'Harvey', 19)]" - ] - }, - "execution_count": 15, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# TODO: Sort the list by the length of their full name\n", - "'''\n", - "def no_name(player):\n", - " return len(player[0]) + len(player[1])\n", - "'''\n", - "sorted(owhockey_badgers, key = lambda player : len(player[0]) + len(player[1]))" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### OK, I can sort a list of tuples....what about a list of dictionaries?" - ] - }, - { - "cell_type": "code", - "execution_count": 16, + "execution_count": 19, "metadata": {}, "outputs": [ { "data": { "text/plain": [ - "[{'name': 'Calvin', 'year': 2000},\n", - " {'name': 'Blanc', 'year': 1990, 'speed': 250},\n", - " {'name': 'Alexandria', 'year': 1980, 'speed': 100}]" + "[{'first': 'Becky', 'last': 'Brown', 'age': 52},\n", + " {'first': 'Sally', 'last': 'Fields', 'age': 47},\n", + " {'first': 'Sam', 'last': 'Luna-Nelson', 'age': 26},\n", + " {'first': 'Louis', 'last': 'Oliphant', 'age': 53}]" ] }, - "execution_count": 16, + "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ + "# TODO: sort the people list of dictionaries by the last name\n", "\n", - "hurricanes = [\n", - " {\"name\": \"Calvin\", \"year\": 2000},\n", - " {\"name\": \"Alexandria\", \"year\": 1980, \"speed\": 100},\n", - " {\"name\": \"Blanc\", \"year\": 1990, \"speed\": 250},\n", - "]\n", - "\n", - "# call sorted on hurricanes and use a lambda expression to grab the year\n", - "sorted(hurricanes, key = lambda d : d[\"year\"], reverse=True)\n" - ] - }, - { - "cell_type": "code", - "execution_count": 17, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "[{'name': 'Alexandria', 'year': 1980, 'speed': 100},\n", - " {'name': 'Blanc', 'year': 1990, 'speed': 250},\n", - " {'name': 'Calvin', 'year': 2000}]" - ] - }, - "execution_count": 17, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# sort hurricanes alphabetically by name\n", - "# for you to do on your own...see the above example\n", - "sorted(hurricanes, key = lambda d : d[\"name\"])" + "sorted(people, key = lambda p : p['last'])" ] }, { "cell_type": "code", - "execution_count": 18, + "execution_count": 21, "metadata": {}, "outputs": [ { "data": { "text/plain": [ - "[{'name': 'Calvin', 'year': 2000},\n", - " {'name': 'Alexandria', 'year': 1980, 'speed': 100},\n", - " {'name': 'Blanc', 'year': 1990, 'speed': 250}]" + "[{'first': 'Becky', 'last': 'Brown', 'age': 52},\n", + " {'first': 'Sally', 'last': 'Fields', 'age': 47},\n", + " {'first': 'Louis', 'last': 'Oliphant', 'age': 53},\n", + " {'first': 'Sam', 'last': 'Luna-Nelson', 'age': 26}]" ] }, - "execution_count": 18, + "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ - "# on your own, sort hurricanes by speed.....\n", - "sorted(hurricanes, key = lambda d : d.get(\"speed\", 0))" + "# TODO: Sort the people list of dictionaries by the LENGTH of their last name\n", + "\n", + "sorted(people, key = lambda p : len(p['last']))\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ - "### This is all great, but what I'd really like to do is to sort dictionaries!\n" + "### This is all great, but what I'd really like to do is to sort dictionaries!\n", + "\n", + "From Python 3.7 onwards, the standard dict type maintains insertion order by default ([see here](https://mail.python.org/pipermail/python-dev/2017-December/151283.html)), so a dictionary could be ordered, but what happens if you try and sort a dictionary?" ] }, { "cell_type": "code", - "execution_count": 19, + "execution_count": 22, "metadata": {}, "outputs": [ { @@ -735,7 +779,7 @@ "['ala mode', 'cookie', 'donut', 'hot dog', 'loaf', 'milk', 'pie']" ] }, - "execution_count": 19, + "execution_count": 22, "metadata": {}, "output_type": "execute_result" } @@ -750,12 +794,12 @@ " 'hot dog': 4.99}\n", "\n", "# sorted (dict) returns a list of the keys sorted\n", - "sorted(menu)\n" + "sorted(menu)" ] }, { "cell_type": "code", - "execution_count": 20, + "execution_count": 23, "metadata": {}, "outputs": [ { @@ -764,7 +808,7 @@ "dict_items([('pie', 3.95), ('ala mode', 1.5), ('donut', 1.25), ('cookie', 0.79), ('milk', 1.65), ('loaf', 5.99), ('hot dog', 4.99)])" ] }, - "execution_count": 20, + "execution_count": 23, "metadata": {}, "output_type": "execute_result" } @@ -776,7 +820,7 @@ }, { "cell_type": "code", - "execution_count": 21, + "execution_count": 24, "metadata": {}, "outputs": [ { @@ -791,7 +835,7 @@ " ('pie', 3.95)]" ] }, - "execution_count": 21, + "execution_count": 24, "metadata": {}, "output_type": "execute_result" } @@ -801,12 +845,12 @@ "\n", "# let's sort menu.items() the same way we sorted a list of tuples\n", "\n", - "sorted(menu.items(), key = lambda t : t[0] ) # set the sorting key to a lambda expressoin" + "sorted(menu.items(), key = lambda t : t[0] ) # set the sorting key to a lambda expression" ] }, { "cell_type": "code", - "execution_count": 22, + "execution_count": 25, "metadata": {}, "outputs": [ { @@ -821,19 +865,19 @@ " 'pie': 3.95}" ] }, - "execution_count": 22, + "execution_count": 25, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# now let's turn this list of tuples into a dict\n", - "dict(sorted(menu.items(), key=lambda thing: thing[0]))" + "dict(sorted(menu.items(), key = lambda t : t[0]))" ] }, { "cell_type": "code", - "execution_count": 23, + "execution_count": 26, "metadata": {}, "outputs": [ { @@ -848,41 +892,14 @@ " 'loaf': 5.99}" ] }, - "execution_count": 23, + "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# can you change the previous code to sort by price? \n", - "dict(sorted(menu.items(), key=lambda thing: thing[1]))" - ] - }, - { - "cell_type": "code", - "execution_count": 24, - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "{'pie': 3.95,\n", - " 'milk': 1.65,\n", - " 'loaf': 5.99,\n", - " 'donut': 1.25,\n", - " 'cookie': 0.79,\n", - " 'hot dog': 4.99,\n", - " 'ala mode': 1.5}" - ] - }, - "execution_count": 24, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# can you sort the dictionary by the length of the name? \n", - "dict(sorted(menu.items(), key=lambda thing: len(thing[0])))" + "dict(sorted(menu.items(), key = lambda t : t[1]))" ] }, { @@ -894,19 +911,40 @@ }, { "cell_type": "code", - "execution_count": 25, + "execution_count": 30, "metadata": {}, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[1, 2, 3, 4, 5, 6, 8]\n", + "[{'one': 2, 'two': 1}, {'one': 5, 'two': 8}, {'one': 7, 'two': 6}]\n", + "{'four': 43, 'one': 8, 'three': 12, 'two': 3}\n", + "{'two': 3, 'one': 8, 'three': 12, 'four': 43}\n" + ] + } + ], "source": [ "# Practice sorting a list of tuples\n", + "print(sorted((5,3,4,6,2,1,8)))\n", "\n", "# Practice sorting a list of dictionaries \n", - "\n", + "print(sorted([{'one':5,'two':8},{'one':2,'two':1},{'one':7,'two':6}],key=lambda p: p['one']))\n", "# Practice sorting a dictionary by keys\n", + "print(dict(sorted({'one':8,'two':3,'three':12,'four':43}.items(),key=lambda t: t[0])))\n", "\n", "# Practice sorting a dictionary by values\n", + "print(dict(sorted({'one':8,'two':3,'three':12,'four':43}.items(),key=lambda t: t[1])))\n", "\n" ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] } ], "metadata": { @@ -925,7 +963,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.11.5" + "version": "3.10.12" } }, "nbformat": 4, -- GitLab