Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Math 152: Intro to Mathematical Software
2017-01-20
Kiran Kedlaya; University of California, San Diego
adapted from lectures by William Stein, University of Washington
**Lecture 5: Dicts and Classes **
Guest lecturer: William Stein (Professor, University of Washington; CEO, SageMath Inc.)
Another important data structure: the Python dictionary
A Python dictionary is the Python version of what computer scientists might call an "associative array".
It's what us mathematicians call a "function" from one finite set to another ( not to be confused with a Python "function", which is really a subroutine).
Aside: Python has a form of flow control for catching runtime errors.
You can also use get
and specify a default if there is no key in the dict
The keys (inputs) of a Python dictionary can be any object x in Python where hash(x)
doesn't give an error.
In practice, hash(x)
is supposed to work if and only if x
is immutable, i.e., really can't change.
We saw tuples briefly in the previous lecture.
Tuples are sort of like lists, but you can't change the objects they point to or the number of things they point to.
Hence... they have a chance to be immutable:
Not all tuples are immutable. For example:
Exercise: Which of the following are immutable, i.e., hash
-able, so they can be used as keys for a dictionary?
the string "Foo"
the empty list []
the number 3.14
the dictionary {7:10, 3:8}
the tuple ('foo', 'bar')
Make a dictionary that has all the immutable objects above as keys... and anything you want (hashable or not) as values.
Here's a dictionary with a Python function as a value:
Using dicts with data and functions, you could try to model mathematical objects and work with them.
But the notation is very awkward!
Python classes do much the same thing, with vastly nicer notation!
Python Classes
Python classes let you easily create custom Python objects. They are a fantastic way of organizing math-related code (as well as many other types of code).
Example:
Exercise:
Copy the above code and make a class Vector3 that models a vector in 3-dimensional space.
If you have time, also include a __sub__
method, to subtract one vector from another, and test that v - w works.