Skip to content

Write exercises for reworked week 5 content #29

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: python-course-23-24
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
198 changes: 166 additions & 32 deletions week5/w5.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@
"square = {\n",
" \"width\": 3,\n",
" \"colour\": \"blue\"\n",
"}"
"}\n"
]
},
{
Expand All @@ -70,7 +70,9 @@
"source": [
"def calculate_area(square):\n",
" # Remember that `**` is the power operator\n",
" return square[\"width\"] ** 2"
" return square[\"width\"] ** 2\n",
"\n",
"print(calculate_area(square))\n"
]
},
{
Expand Down Expand Up @@ -111,7 +113,7 @@
"class Square:\n",
" pass\n",
"\n",
"my_square = Square()"
"my_square = Square()\n"
]
},
{
Expand Down Expand Up @@ -168,12 +170,12 @@
" def __init__(self, width, colour):\n",
" self.width = width\n",
" self.colour = colour\n",
" \n",
"\n",
" def calculate_area(self):\n",
" return self.width ** 2\n",
"\n",
"my_square = Square(3, \"blue\")\n",
"print(my_square.calculate_area)"
"print(my_square.calculate_area())\n"
]
},
{
Expand All @@ -193,7 +195,7 @@
"source": [
"print(\"Hello\".__class__)\n",
"print((100).__class__)\n",
"print(print.__class__)"
"print(print.__class__)\n"
]
},
{
Expand Down Expand Up @@ -263,7 +265,7 @@
"outputs": [],
"source": [
"import random\n",
"print(random.randint(0, 10))"
"print(random.randint(0, 10))\n"
]
},
{
Expand All @@ -282,7 +284,7 @@
"outputs": [],
"source": [
"from random import randint\n",
"print(randint(0, 10))"
"print(randint(0, 10))\n"
]
},
{
Expand Down Expand Up @@ -332,7 +334,7 @@
"outputs": [],
"source": [
"from emoji import emojize\n",
"print(emojize(\":thumbs_up:\"))"
"print(emojize(\":thumbs_up:\"))\n"
]
},
{
Expand Down Expand Up @@ -380,7 +382,11 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"## Readability counts!"
"## Readability counts!\n",
"\n",
"> “Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.”\n",
">\n",
"> -- John F. Woods"
]
},
{
Expand Down Expand Up @@ -448,14 +454,14 @@
" if nTwo > nThree != False:\n",
" return 1\n",
" else:\n",
" ans += 1 \n",
" ans += 1\n",
" elif True:\n",
" return 1 if nOne > nThree else 2\n",
" return ans\n",
" \n",
"\n",
"print(x([5, 8, 0, 3], [4, 7, 2, 4], [9, 4, 6, 1]))\n",
"\n",
"# what did I just read"
"# what did I just read\n"
]
},
{
Expand All @@ -473,17 +479,17 @@
"source": [
"def most_rounds_won(player_breakdown: list[list[int]]) -> int:\n",
" \"\"\"Get the index of the player who won the most rounds.\n",
" \n",
"\n",
" Args:\n",
" player_breakdown: A list containing the lists of scores for each player,\n",
" which doesn't contain duplicates.\n",
" \n",
"\n",
" Returns:\n",
" The index in the input list of the player who won the most rounds.\n",
" \"\"\"\n",
" players_in_quiz = len(player_breakdown)\n",
" rounds_in_quiz = len(player_breakdown[0])\n",
" \n",
"\n",
" # Regroup (transpose/zip) the 2D list to compare more easily\n",
" # Example: [[1, 2, 3], [4, 5, 6]] into [[1, 4], [2, 5], [3, 6]]\n",
" round_breakdown = [\n",
Expand All @@ -503,7 +509,7 @@
" return counts.index(max(counts))\n",
"\n",
"\n",
"print(most_rounds_won([[5, 8, 0, 3], [4, 7, 2, 4], [9, 4, 6, 1]]))"
"print(most_rounds_won([[5, 8, 0, 3], [4, 7, 2, 4], [9, 4, 6, 1]]))\n"
]
},
{
Expand Down Expand Up @@ -576,7 +582,10 @@
"source": [
"# This is a function which takes an integer as its parameter, and returns a boolean\n",
"def is_even(number: int) -> bool:\n",
" return number % 2 == 0"
" return number % 2 == 0\n",
"\n",
"print(is_even(2))\n",
"print(is_even(3))\n"
]
},
{
Expand All @@ -601,10 +610,10 @@
"source": [
"def say_hello(name: str) -> None:\n",
" print(f\"Hello {name}!\")\n",
" \n",
"\n",
"say_hello(\"The xSoc course\")\n",
"# The interpreter still allows this, even though it is the wrong type\n",
"say_hello(123)"
"say_hello(123)\n"
]
},
{
Expand Down Expand Up @@ -637,7 +646,7 @@
"This is a multi-line string, which isn't assigned to anything.\n",
"\n",
"This is how we write multi-line comments in python.\n",
"\"\"\""
"\"\"\"\n"
]
},
{
Expand All @@ -658,8 +667,8 @@
" \"\"\"Takes a number, and returns its square.\"\"\"\n",
" return number ** 2\n",
"\n",
"print(\"The square function: {square.__doc__}\")\n",
"print(square(2))"
"print(f\"The square function: `{square.__doc__}`\")\n",
"print(square(2))\n"
]
},
{
Expand All @@ -683,44 +692,169 @@
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Extension: List comprehensions\n",
"\n"
"# Week 5 Exercises"
]
},
{
"attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"---"
"## Exercise 1\n",
"\n",
"In the notes above, we saw an example of turning a dictionary representation of data and methods for a square into a class.\n",
"\n",
"Below is another dictionary representation of some data and methods, this time describing cars. Your job is to turn it into a simple class which does the same thing."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"car = {\n",
" \"miles_per_gallon\": 10,\n",
" \"fuel_tank_size\": 50,\n",
" \"colour\": \"blue\",\n",
"}\n",
"\n",
"def calculate_range(car):\n",
" return car[\"miles_per_gallon\"] * car[\"fuel_tank_size\"]\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Create a class for a car with the same properties and methods as above\n",
"# If you get stuck, try looking back at the notes and see how we did it\n",
"# for the square example.\n",
"\n",
"\n",
"# Create an object instance of the class with the data from the above\n",
"\n",
"\n",
"# Call the range method of the object to find its range\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Week 5 Exercises"
"## Exercise 2\n",
"\n",
"In this exercise, we are going to combine what we've learnt about libraries with what we know about classes to do something useful(-ish).\n",
"\n",
"The `requests` library lets us make http requests to access content on the web. As it is not part of the standard library **you will need to install it yourself** using the `pip` command line tool we discussed above.\n",
"\n",
"Once the library is installed, the next thing to do is normally to look at its documentation. For `requests`, the quickstart page can be found here: https://requests.readthedocs.io/en/latest/user/quickstart/ . This shows us how to use it to make a web request:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import requests\n",
"\n",
"response = requests.get(\"https://xkcd.com/\")\n",
"print(response)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Exercise n"
"However, if you run this code it doesn't give you what you might expect! Instead of giving you the HTML for the website, it just prints \"<Response [200]>\"!\n",
"\n",
"This is because `response` is actually an object, which contains lots of different data about the response to the request we made! We can confirm this as we say before by using `__class__`"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(response.__class__)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Your second challenge is to try to get the HTML content from this response object, so you can read what the website says. This might seem impossible at first, since you don't know what the properties and methods the class has, but again documentation comes to the rescue!\n",
"\n",
"Look at this website: https://requests.readthedocs.io/en/latest/api/#requests.Response , and try to find the property which contains the HTML code, and print it out."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Print out the HTML of the response using a property of the object\n",
"# from the documentation\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"As some extra fun(?) you can look at the other properties and methods of the classes and experiment with what they do!\n",
"\n",
"Hopefully you can see how objects are useful in the real world, especially when interacting with libraries, as lots of them are just collections of objects."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Week 5 Bonus Exercises"
"# Exercise 3\n",
"\n",
"This exercise is about writing readable code. Below is some code which is designed to pairwise multiply two lists of integers. It is **very bad™** , and your job is to rewrite it to make it more readable."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def m(l):\n",
" while len(l[0]) != len(l[0]):\n",
" return\n",
" my_list = [0] * len(l[1])\n",
" for thisIsAN_index in range(len(l[1])):\n",
" my_list[thisIsAN_index] = l[0][thisIsAN_index] * l[1][thisIsAN_index]\n",
" return my_list\n",
"print(m([[1,2,3,4,5,6],[6,5,4,3,2,1]]))\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Challenge n"
"As a reminder from the notes above, these a some things you may want to think about when re-writing the code to make it more readable:\n",
"\n",
"- Meaningful and consistent variable names\n",
"- Use empty lines to split up sections\n",
"- Be consistent with indentations\n",
"- Add type hints\n",
"- Add docstrings to describe what functions do"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Re-write the code above so it does the same thing but is more readable\n"
]
},
{
Expand Down Expand Up @@ -748,7 +882,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.3"
"version": "3.11.5"
},
"vscode": {
"interpreter": {
Expand Down
Loading