Skip to content
Snippets Groups Projects
Commit e0b8a991 authored by LOUIS TYRRELL OLIPHANT's avatar LOUIS TYRRELL OLIPHANT
Browse files

Finished Lec 23

parent 23c7e5c8
No related branches found
No related tags found
No related merge requests found
...@@ -45,6 +45,7 @@ ...@@ -45,6 +45,7 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
<<<<<<< HEAD
"execution_count": 1, "execution_count": 1,
"metadata": {}, "metadata": {},
"outputs": [ "outputs": [
...@@ -59,6 +60,11 @@ ...@@ -59,6 +60,11 @@
"output_type": "execute_result" "output_type": "execute_result"
} }
], ],
=======
"execution_count": null,
"metadata": {},
"outputs": [],
>>>>>>> f9e9c99 (finished lec 23 function references)
"source": [ "source": [
"# Warmup 2: Trace Recursion by hand .... possible exam question\n", "# Warmup 2: Trace Recursion by hand .... possible exam question\n",
"\n", "\n",
...@@ -85,11 +91,19 @@ ...@@ -85,11 +91,19 @@
"\n", "\n",
"- [Python for Everybody, 10.8](https://runestone.academy/ns/books/published/py4e-int/dictionaries/toctree.html)\n", "- [Python for Everybody, 10.8](https://runestone.academy/ns/books/published/py4e-int/dictionaries/toctree.html)\n",
"\n", "\n",
<<<<<<< HEAD
"As we have learned previously, all variables in Python refer to objects.\n", "As we have learned previously, all variables in Python refer to objects.\n",
"\n", "\n",
"This is also true for functions -- their name refers to a function object, and it gives us more power as programmers.\n", "This is also true for functions -- their name refers to a function object, and it gives us more power as programmers.\n",
"\n", "\n",
"## Learning Objectives\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", "\n",
"- Define a function reference and trace code that uses 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", "- Explain the default use of sorted() on lists of tuples, and dictionaries.\n",
...@@ -98,6 +112,7 @@ ...@@ -98,6 +112,7 @@
] ]
}, },
{ {
<<<<<<< HEAD
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {}, "metadata": {},
"source": [ "source": [
...@@ -137,6 +152,8 @@ ...@@ -137,6 +152,8 @@
] ]
}, },
{ {
=======
>>>>>>> f9e9c99 (finished lec 23 function references)
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": {}, "metadata": {},
...@@ -146,6 +163,7 @@ ...@@ -146,6 +163,7 @@
"# try this in Python Tutor\n", "# try this in Python Tutor\n",
"\n", "\n",
"x = [1,2,3]\n", "x = [1,2,3]\n",
<<<<<<< HEAD
"y = x\n", "y = x\n",
"\n", "\n",
"def f(some_list): # what is f? \n", "def f(some_list): # what is f? \n",
...@@ -156,6 +174,22 @@ ...@@ -156,6 +174,22 @@
"g = f # what is g?\n", "g = f # what is g?\n",
"\n", "\n",
"# TODO: Try calling the function using the variable g\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 @@ ...@@ -181,12 +215,17 @@
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {}, "metadata": {},
"source": [ "source": [
<<<<<<< HEAD
"## Functions can be passed as arguments!\n", "## 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." "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", "cell_type": "code",
<<<<<<< HEAD
"execution_count": 2, "execution_count": 2,
"metadata": {}, "metadata": {},
"outputs": [ "outputs": [
...@@ -202,6 +241,13 @@ ...@@ -202,6 +241,13 @@
], ],
"source": [ "source": [
"# function references can be passed as arguments ...Wow!\n", "# 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", "\n",
"# first: try this in Python Tutor\n", "# first: try this in Python Tutor\n",
"\n", "\n",
...@@ -291,7 +337,15 @@ ...@@ -291,7 +337,15 @@
"source": [ "source": [
"We already did the math behind `manhattan_distance` and `euclidean_distance` for you!\n", "We already did the math behind `manhattan_distance` and `euclidean_distance` for you!\n",
"\n", "\n",
<<<<<<< HEAD
"**Hint:** `distance_algo` should be a reference to a function that calculates distance between two points.\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",
>>>>>>> f9e9c99 (finished lec 23 function references)
"\n", "\n",
"Then, call calculate_distances measuring first in manhattan_distance, then euclidean_distance." "Then, call calculate_distances measuring first in manhattan_distance, then euclidean_distance."
] ]
...@@ -326,7 +380,18 @@ ...@@ -326,7 +380,18 @@
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {}, "metadata": {},
"source": [ "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"
=======
"### 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 @@ ...@@ -335,14 +400,20 @@
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
<<<<<<< HEAD
"# first... did you know that sort/sorted takes a 2nd argument called reverse?\n", "# first... did you know that sort/sorted takes a 2nd argument called reverse?\n",
"\n", "\n",
"populations = [55, 77, 33, 99, 22]\n", "populations = [55, 77, 33, 99, 22]\n",
"# TODO: sort populations in reverse" "# 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", "cell_type": "code",
<<<<<<< HEAD
"execution_count": 1, "execution_count": 1,
"metadata": {}, "metadata": {},
"outputs": [ "outputs": [
...@@ -362,6 +433,40 @@ ...@@ -362,6 +433,40 @@
"output_type": "execute_result" "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": [ "source": [
"# Sorting part 1....how are lists of tuples sorted?\n", "# Sorting part 1....how are lists of tuples sorted?\n",
"# olympic womens hockey badgers...first, last, age\n", "# olympic womens hockey badgers...first, last, age\n",
...@@ -371,7 +476,12 @@ ...@@ -371,7 +476,12 @@
" (\"Amanda\", \"Kessel\", 30),\n", " (\"Amanda\", \"Kessel\", 30),\n",
" (\"Alex\", \"Cavalenni\", 30), \n", " (\"Alex\", \"Cavalenni\", 30), \n",
" (\"Caroline\", \"Harvey\", 19),\n", " (\"Caroline\", \"Harvey\", 19),\n",
<<<<<<< HEAD
" (\"Abbey\", \"Roque\", 24)\n", " (\"Abbey\", \"Roque\", 24)\n",
=======
" (\"Abbey\", \"Roquet\", 24),\n",
" (\"Abbey\", \"Roques\", 27)\n",
>>>>>>> f9e9c99 (finished lec 23 function references)
" ]\n", " ]\n",
"\n", "\n",
"\n", "\n",
...@@ -381,6 +491,20 @@ ...@@ -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", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": {}, "metadata": {},
...@@ -396,7 +520,20 @@ ...@@ -396,7 +520,20 @@
"def select2(some_tuple):\n", "def select2(some_tuple):\n",
" return some_tuple[2]\n", " return some_tuple[2]\n",
"\n", "\n",
<<<<<<< HEAD
"# Test these functions on the tuple (\"Mike\", \"Gurmail\", \"Cole\")\n" "# 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 @@ ...@@ -408,6 +545,7 @@
"# call sorted using the 'key' argument \n", "# call sorted using the 'key' argument \n",
"# sort and sorted can take a parameter named key\n", "# sort and sorted can take a parameter named key\n",
"# key is a reference to a function!\n", "# key is a reference to a function!\n",
<<<<<<< HEAD
"sorted(owhockey_badgers, key=select2)" "sorted(owhockey_badgers, key=select2)"
] ]
}, },
...@@ -427,12 +565,18 @@ ...@@ -427,12 +565,18 @@
"outputs": [], "outputs": [],
"source": [ "source": [
"# sort the list of tuples based on the age\n" "# 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", "cell_type": "markdown",
"metadata": {}, "metadata": {},
"source": [ "source": [
<<<<<<< HEAD
"### Using `lambda`\n", "### Using `lambda`\n",
"- `lambda` functions are a way to abstract a function reference\n", "- `lambda` functions are a way to abstract a function reference\n",
"- lambdas are simple functions with:\n", "- lambdas are simple functions with:\n",
...@@ -446,6 +590,13 @@ ...@@ -446,6 +590,13 @@
"```python \n", "```python \n",
"lambda parameters: expression\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 @@ ...@@ -454,6 +605,7 @@
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
<<<<<<< HEAD
"# sorting part 3....using lambdas\n", "# sorting part 3....using lambdas\n",
"\n", "\n",
"'''\n", "'''\n",
...@@ -464,12 +616,96 @@ ...@@ -464,12 +616,96 @@
"sorted(owhockey_badgers, key = lambda each_tuple : each_tuple[-1])\n", "sorted(owhockey_badgers, key = lambda each_tuple : each_tuple[-1])\n",
"\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 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", "# and returns each_tuple[-1] (the last element)\n",
"# the variable 'each_tuple' is like a function parameter" "# the variable 'each_tuple' is like a function parameter"
] ]
}, },
{ {
"cell_type": "code", "cell_type": "code",
<<<<<<< HEAD
"execution_count": 5, "execution_count": 5,
"metadata": {}, "metadata": {},
"outputs": [ "outputs": [
...@@ -490,6 +726,15 @@ ...@@ -490,6 +726,15 @@
"def no_name(x):\n", "def no_name(x):\n",
" return len(x[0])\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 @@ ...@@ -498,13 +743,20 @@
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
<<<<<<< HEAD
"# TODO: Sort the list by the length of their full name\n" "# 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", "cell_type": "markdown",
"metadata": {}, "metadata": {},
"source": [ "source": [
<<<<<<< HEAD
"### OK, I can sort a list of tuples....what about a list of dictionaries?" "### OK, I can sort a list of tuples....what about a list of dictionaries?"
] ]
}, },
...@@ -562,6 +814,11 @@ ...@@ -562,6 +814,11 @@
"metadata": {}, "metadata": {},
"source": [ "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"
=======
"### 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 @@ ...@@ -602,7 +859,11 @@
"\n", "\n",
"# let's sort menu.items() the same way we sorted a list of tuples\n", "# let's sort menu.items() the same way we sorted a list of tuples\n",
"\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 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 @@ ...@@ -625,6 +886,7 @@
] ]
}, },
{ {
<<<<<<< HEAD
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": null,
"metadata": {}, "metadata": {},
...@@ -634,6 +896,8 @@ ...@@ -634,6 +896,8 @@
] ]
}, },
{ {
=======
>>>>>>> f9e9c99 (finished lec 23 function references)
"cell_type": "markdown", "cell_type": "markdown",
"metadata": {}, "metadata": {},
"source": [ "source": [
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment