{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# MCS 260 Fall 2021 Worksheet 10\n",
"\n",
"* Course instructor: Emily Dumas"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Topics\n",
"\n",
"This worksheet focuses on **object-oriented programming**.\n",
"\n",
"(While last week included some lecture material on **higher-order functions and lamdba**, they are not included on this worksheet because you'll work with those topics a lot on Project 3. But you can check out the [higher/](https://github.com/emilydumas/mcs260fall2021/tree/main/samplecode/higher) folder in the course sample code repo to see several examples, including ones that were mentioned in lecture but not covered in detail.)\n",
"\n",
"## Problem 1 treated differently\n",
"\n",
"Following the new policy, Problem 1 is different in that:\n",
"* **Tuesday lab students:** Problem 1 will be presented and solved as a group, in a discussion led by your TA.\n",
"* **Thursday lab students:** Please attempt problem 1 before coming to lab. Bring a solution, or bring questions. The problem will be discussed as a group.\n",
"\n",
"## Resources\n",
"\n",
"The main course materials to refer to for this worksheet are:\n",
"\n",
"* [Sample programs](https://github.com/emilydumas/mcs260fall2021/tree/main/samplecode)\n",
"* [Lecture 25 - OOP 1](https://www.dumas.io/teaching/2021/fall/mcs260/slides/lecture25.html)\n",
"* [Lecture 26 - OOP 2 (overloading)](https://www.dumas.io/teaching/2021/fall/mcs260/slides/lecture26.html)\n",
"* [Lecture 27 - OOP 3 (inheritance)](https://www.dumas.io/teaching/2021/fall/mcs260/slides/lecture27.html)\n",
"* [Downey's book](https://greenteapress.com/thinkpython2/html/)\n",
"\n",
"(Lecture videos are not linked on worksheets, but are also useful to review while working on worksheets. Video links can be found in the course [course Blackboard site](https://uic.blackboard.com/ultra/courses/_202683_1/cl/outline).)\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 1. Segment class\n",
"\n",
"Analogous to the classes discussed in our OOP lectures (for geometric objects Circle and Rectangle), create a Python class called Segment to store a line segment in the plane. The constructor should accept four arguments: x0,y0,x1,y1. The point (x0,y0) is then one endpoint of the segment, and (x1,y1) is the other endpoint. All four constructor arguments should be stored as attributes.\n",
"\n",
"The following methods should be included:\n",
"* `translate(dx,dy)` - move the segment horizontally by `dx` and vertically by `dy`. This should modify the object, not returning anything.\n",
"* `scale(factor)` - increase the length of the segment by a factor of `factor`, keeping the center point the same. **This is tricky, because the center point is not part of the data stored in the class! Feel free to skip this at first and come back to it later.**\n",
"* `__str__()` - make a reasonable human-readable string representation that includes the values of x0,y0,x1,y1.\n",
"* `length()` - returns a float, the distance between the endpoints of the segment.\n",
"\n",
"Also, read the next problem before you start work on this."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 2. Equality for segments\n",
"\n",
"This problem builds on the Segment class from problem 1.\n",
"\n",
"Suppose the Segment class from Problem 2 is stored in a file `geom.py`. Write a program to test the Segment class. It should do the following:\n",
"\n",
"* Create a segment and check that the attributes x0,y1, etc. exist.\n",
"* Scale a segment and confirm that the new endpoints are as expected.\n",
"* Translate a segment and confirm that the new endpoints are as expected.\n",
"* Test that a segment that you choose to ensure its length is computed correctly.\n",
"\n",
"## IMPORTANT NOTE\n",
"\n",
"Any time you are tempted to test whether two floats are equal, please instead use a check of whether they differ by a very small amount, e.g. instead of\n",
"```\n",
"if x == y:\n",
" # stuff\n",
"```\n",
"use\n",
"```\n",
"if abs(x-y) < 0.000000001:\n",
" # stuff\n",
"```\n",
"This will help to avoid problems created by the fact that float operations are only approximations of the associated operations on real numbers. For example,\n",
"```\n",
"0.1 + 0.2 == 0.3\n",
"```\n",
"evaluates to `False` because of the slight error in float addition (compared to real number addition), whereas\n",
"```\n",
"abs( 0.3 - (0.1+0.2) ) < 0.000000001\n",
"```\n",
"evaluates to `True`."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 3. Quantity with unit\n",
"\n",
"Below you will find code that defines a class `QuantityWithUnit` that is meant to store float quantities that also have a unit of measurement attached to them, such as `55 m` (55 meters), `2.8 s` (2.8 seconds), or `94.05 kg` (94.05 kilograms). Save it in a file `qwu.py` on your computer, so you can import it with `import qwu`. Read the code and familiarize yourself with what it does. Then try the following:\n",
"\n",
"* Create an instance M of this class to represent 19 kilograms\n",
"* See how the REPL displays that value\n",
"* Try printing M\n",
"* What happens when you add M to itself?\n",
"* What happens when you subtract M from itself?\n",
"* Create an instance T of this class to represent 3600 seconds\n",
"* What happens when you add M and T?\n",
"\n",
"The final product of your work on this question could be a program that demonstrates all of these features."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"class QuantityWithUnit:\n",
" \"\"\"A float quantity that also has a unit name, such as \n",
" kilograms, meters, seconds, etc.\"\"\"\n",
" def __init__(self,qty,unit):\n",
" \"\"\"Create new quantity with units\"\"\"\n",
" self.qty = float(qty)\n",
" self.unit = unit\n",
" def __str__(self):\n",
" \"\"\"Make human-readable string version of quantity\"\"\"\n",
" return \"{} {}\".format(self.qty,self.unit)\n",
" def __repr__(self):\n",
" \"\"\"Make human-readable string version of quantity\"\"\"\n",
" return \"QuantityWithUnits(qty={},unit={})\".format(self.qty,self.unit)\n",
" def __add__(self,other):\n",
" \"\"\"Sum of two quantities requires them to have the same units\"\"\"\n",
" if not isinstance(other,QuantityWithUnits):\n",
" raise TypeError(\"Can only add a QuantityWithUnits to another QuantityWithUnits\")\n",
" if self.unit != other.unit:\n",
" raise ValueError(\"Cannot add quantities with different units: {} and {}\".format(self,other))\n",
" return QuantityWithUnits(self.qty+other.qty,self.unit)\n",
" def __sub__(self,other):\n",
" \"\"\"Difference of two quantities requires them to have the same units\"\"\"\n",
" if not isinstance(other,QuantityWithUnits):\n",
" raise TypeError(\"Can only subtract a QuantityWithUnits from another QuantityWithUnits\")\n",
" if self.unit != other.unit:\n",
" raise ValueError(\"Cannot subtract quantities with different units: {} and {}\".format(self,other))\n",
" return QuantityWithUnits(self.qty-other.qty,self.unit)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 4. Improving the quantity with unit class\n",
"\n",
"You should look at the previous problem before attempting this one, because it presumes familiarity with the `QuantityWithUnit` class.\n",
"\n",
"First, add support for testing equality to `QuantityWithUnit`. Two quantities with unit should be considered equal if the float quantities are equal, and if the units are equal.\n",
"\n",
"Now, consider adding support for multiplication as follows.\n",
"\n",
"Multiplying two quantities with units results in an answer that has a different unit. For example, 11 kilograms multiplied by 20 seconds is equal to 220 kilogram-seconds.\n",
"\n",
"However, it does make sense to multiply a quantity with units by a number that has no units at all. For example, if you have 16 apples that each have a mass of 0.1 kilograms, then the total mass is (0.1kg)\\*16 = 1.6kg.\n",
"\n",
"Add an operator overloading feature to `QuantityWithUnit` that allows such a quantity to be multiplied by a number as long as it is not an instance of `QuantityWithUnit`. If you do this correctly, then the following tests should behave as the comments suggest. These assume that you have `QuantityWithUnit` in a module called `qwu`."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Revision history\n",
"\n",
"* 2021-10-25 Initial release"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.10"
}
},
"nbformat": 4,
"nbformat_minor": 4
}