Skip to content

Commit

Permalink
Revert back examples from doctoal-school migration
Browse files Browse the repository at this point in the history
  • Loading branch information
dpshelio committed Aug 15, 2024
1 parent ba86ec2 commit f99e4fd
Show file tree
Hide file tree
Showing 8 changed files with 172 additions and 101 deletions.
12 changes: 7 additions & 5 deletions ch01python/025containers.ipynb.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,17 +189,17 @@
# ## Tuples

# %% [markdown]
# A `tuple` is an immutable sequence:
#
#
#
# A `tuple` is an immutable sequence. It is like a list, execpt it cannot be changed. It is defined with round brackets.

# %%
my_tuple = ("Hello", "World")

# %%
my_tuple

# %% [markdown]
# Trying to modify one of its values will fail:

# %%
my_tuple[0] = "Goodbye"

Expand All @@ -217,7 +217,7 @@
fish = "Rake" ## OK!

# %% [markdown]
# *Supplementary material*: Try the [online memory visualiser](http://www.pythontutor.com/visualize.html#code=name%20%3D%20%20%22James%20Philip%20John%20Hetherington%22.split%28%22%20%22%29%0A%0Aname%5B0%5D%20%3D%20%22Dr%22%0Aname%5B1%3A3%5D%20%3D%20%5B%22Griffiths-%22%5D%0Aname.append%28%22PhD%22%29%0A%0Aname%20%3D%20%22Bilbo%20Baggins%22&cumulative=false&curInstr=0&heapPrimitives=true&mode=display&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false) for this one.
# *Supplementary material*: Try the [online memory visualiser](http://www.pythontutor.com/visualize.html#code=name+%3D++%22Sir+Michael+Edward+Palin%22.split%28%22+%22%29%0A%0Aname%5B0%5D+%3D+%22Knight%22%0Aname%5B1%3A3%5D+%3D+%5B%22Mike-%22%5D%0Aname.append%28%22FRGS%22%29%0A%0Aname%20%3D%20%22King%20Arthur%22&&mode=display&origin=opt-frontend.js&cumulative=false&heapPrimitives=true&textReferences=false&py=3&rawInputLstJSON=%5B%5D&curInstr=0) for this one.

# %% [markdown]
# ## Memory and containers
Expand Down Expand Up @@ -290,6 +290,8 @@
# %% [markdown]
# Try the [visualiser](http://www.pythontutor.com/visualize.html#code=x%3D%5B%5B'a','b'%5D,'c'%5D%0Ay%3Dx%0Az%3Dx%5B0%3A2%5D%0A%0Ax%5B0%5D%5B1%5D%3D'd'%0Az%5B1%5D%3D'e'&cumulative=false&curInstr=5&heapPrimitives=true&mode=display&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false)
# again.
#
# *Supplementary material*: The copies that we make through slicing are called *shallow copies*: we don't copy all the objects they contain, only the references to them. This is why the nested list in `x[0]` is not copied, so `z[0]` still refers to it. It is possible to actually create copies of all the contents, however deeply nested they are - this is called a *deep copy*. Python provides methods for that in its standard library, in the `copy` module. You can read more about that, as well as about shallow and deep copies, in the [library reference](https://docs.python.org/3/library/copy.html).

# %% [markdown]
# ## Identity versus equality
Expand Down
126 changes: 91 additions & 35 deletions ch01python/028dictionaries.ipynb.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# ---
# jupyter:
# jekyll:
# display_name: Dictionaries
# display_name: Dictionaries and Sets
# jupytext:
# notebook_metadata_filter: -kernelspec,jupytext,jekyll
# text_representation:
Expand All @@ -12,7 +12,7 @@
# ---

# %% [markdown]
# # Dictionaries
# # Dictionaries and Sets

# %% [markdown]
# ## The Python Dictionary
Expand All @@ -34,46 +34,50 @@
# In a dictionary, we look up an element using **another object of our choice**:

# %%
me = {"name": "James", "age": 39, "Jobs": ["Programmer", "Teacher"]}
chapman = {"name": "Graham", "age": 48,
"Jobs": ["Comedian", "Writer"] }

# %%
print(me)
chapman

# %%
print(me["Jobs"])
print(chapman["Jobs"])

# %%
print(type(me))
print(chapman["age"])

# %%
print(type(chapman))

# %% [markdown]
# ## Keys and Values
# ### Keys and Values

# %% [markdown]
# The things we can use to look up with are called **keys**:

# %%
me.keys()
chapman.keys()

# %% [markdown]
# The things we can look up are called **values**:

# %%
me.values()
chapman.values()

# %% [markdown]
# When we test for containment on a `dict` we test on the **keys**:

# %%
"Jobs" in me
"Jobs" in chapman

# %%
"James" in me
"Graham" in chapman

# %%
"James" in me.values()
"Graham" in chapman.values()

# %% [markdown]
# ## Immutable Keys Only
# ### Immutable Keys Only

# %% [markdown]
# The way in which dictionaries work is one of the coolest things in computer science:
Expand All @@ -82,77 +86,129 @@
# You can only use **immutable** things as keys.

# %%
good_match = {("Lamb", "Mint"): True, ("Bacon", "Chocolate"): False}
good_match = {
("Lamb", "Mint"): True,
("Bacon", "Chocolate"): False
}

# %% [markdown]
# but:

# %%
illegal = {[1, 2]: 3}

# %% [markdown]
# *Supplementary material*: You can start to learn about [the 'hash table'](https://www.youtube.com/watch?v=h2d9b_nEzoA). Though this video is **very** advanced I think it's really interesting!
illegal = {
["Lamb", "Mint"]: True,
["Bacon", "Chocolate"]: False
}

# %% [markdown]
# ## No guarantee of order
# *Supplementary material*: You can start to learn about [the 'hash table'](https://www.youtube.com/watch?v=h2d9b_nEzoA). Though this video is **very** advanced, it's really interesting!

# %% [markdown]
# ### No guarantee of order
#
# Another consequence of the way dictionaries work is that there's no guaranteed order among the
# elements:
#
#
#


# %%
my_dict = {"0": 0, "1": 1, "2": 2, "3": 3, "4": 4}
print(my_dict)
print(my_dict.values())

# %% [markdown]
# ### Safe Lookup
#
# Some times you want a program to keep working even when a key is looked up but it's not there.
# Python dictionaries offers that through the `get` method.

# %%
x = {"a": 1, "b": 2}

# %%
x["a"]

# %%
x["fish"]

# %%
x.get("a")

# %%
x.get("fish")

# %% [markdown]
# By default `get` returns `None` if the key searched is not in the dictionary.
# However, you can change that default by adding what's the value you want it to return.

# %%
x.get("fish", "tuna") == "tuna"

# %% [markdown]
# ## Sets

# %% [markdown]
# A set is a `list` which cannot contain the same element twice.
# We make one by calling `set()` on any sequence, e.g. a list or string.

# %%
university = "University College London"
unique_letters = set(university)
name = "Graham Chapman"
unique_letters = set(name)

# %%
unique_letters

# %% [markdown]
# Or by defining a literal like a dictionary, but without the colons:

# %%
primes_below_ten = { 2, 3, 5, 7}

# %%
print(type(unique_letters))
print(type(primes_below_ten))


# %%
unique_letters

# %% [markdown]
# This will be easier to read if we turn the set of letters back into a string, with `join`:

# %%
print("".join(unique_letters))

# %% [markdown]
# `join` uses the character give to be what joins the sequence given:

# %%
"".join(["a", "b", "c"])
"-".join(["a", "b", "c"])

# %% [markdown]
# It has no particular order, but is really useful for checking or storing **unique** values.
# Note that a set has no particular order, but is really useful for checking or storing **unique** values.

# %%
alist = [1, 2, 3]
is_unique = len(set(alist)) == len(alist)
print(is_unique)

# %% [markdown]
# ## Safe Lookup
# Set operations work as in mathematics:

# %%
x = {"a": 1, "b": 2}
x = set("Hello")
y = set("Goodbye")

# %%
x["a"]
x & y # Intersection

# %%
x["fish"]
x | y # Union

# %%
x.get("a")
y - x # y intersection with complement of x: letters in Goodbye but not in Hello

# %%
x.get("fish")
# %% [markdown]
# Your programs will be faster and more readable if you use the appropriate container type for your data's meaning.
# Always use a set for lists which can't in principle contain the same data twice, always use a dictionary for anything
# which feels like a mapping from keys to values.

# %%
x.get("fish", "tuna") == "tuna"
28 changes: 15 additions & 13 deletions ch01python/029structures.ipynb.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,22 +22,24 @@
# data. Later in the course, we'll see how we can define our own types, with their own attributes, properties, and methods. But probably the most common approach is to use nested structures of lists, dictionaries, and sets to model our data. For example, an address might be modelled as a dictionary with appropriately named fields:

# %%
UCL = {'City': 'London',
'Street': 'Gower Street',
'Postcode': 'WC1E 6BT'}
UCL = {
'City': 'London',
'Street': 'Gower Street',
'Postcode': 'WC1E 6BT'
}

# %%
MyHouse = {
Chapman_house = {
'City': 'London',
'Street': 'Waterson Street',
'Postcode': 'E2 8HH'
'Street': 'Southwood ln',
'Postcode': 'N6 5TB'
}

# %% [markdown]
# A collection of people's addresses is then a list of dictionaries:

# %%
addresses = [UCL, MyHouse]
addresses = [UCL, Chapman_house]

# %%
addresses
Expand All @@ -46,10 +48,10 @@
# A more complicated data structure, for example for a census database, might have a list of residents or employees at each address:

# %%
UCL["People"] = ["Clare", "James", "Owain"]
UCL['people'] = ['Jeremy','Leonard', 'James', 'Henry']

# %%
MyHouse["People"] = ["Sue", "James"]
Chapman_house["People"] = ["Graham", "David"]

# %%
addresses
Expand Down Expand Up @@ -90,9 +92,9 @@
# Create an example instance, in a notebook, of a simple structure for your maze:

# %% [markdown]
# * The living room can hold 2 people. James is currently there. You can go outside to the garden, or upstairs to the bedroom, or north to the kitchen.
# * The living room can hold 2 people. Graham is currently there. You can go outside to the garden, or upstairs to the bedroom, or north to the kitchen.
# * From the kitchen, you can go south to the living room. It fits 1 person.
# * From the garden you can go inside to living room. It fits 3 people. Sue is currently there.
# * From the garden you can go inside to living room. It fits 3 people. David is currently there.
# * From the bedroom, you can go downstairs. You can also jump out of the window to the garden. It fits 2 people.

# %% [markdown]
Expand All @@ -107,8 +109,8 @@

# %%
cities = [
{"name": "London", "capacity": 8, "residents": ["Me", "Sue"]},
{"name": "Edinburgh", "capacity": 1, "residents": ["Dave"]},
{"name": "London", "capacity": 8, "residents": ["Graham", "David"]},
{"name": "Edinburgh", "capacity": 1, "residents": ["Henry"]},
{"name": "Cardiff", "capacity": 1, "residents": []},
]

Expand Down
Loading

0 comments on commit f99e4fd

Please sign in to comment.