Skip to content
Snippets Groups Projects
Commit 649f6765 authored by Andy Kuemmel's avatar Andy Kuemmel
Browse files

Update f22/andy_lec_notes/lec20_Oct24_Tuples/lec20_tuples_template.ipynb

Deleted f22/andy_lec_notes/lec20_Oct24_Tuples/lec20_tuples_complete.ipynb
parent 50603bb0
No related branches found
No related tags found
No related merge requests found
%% Cell type:markdown id: tags:
## Warmups
%% Cell type:code id: tags:
``` python
from collections import namedtuple
# we are going to learn about this today !
```
%% Cell type:code id: tags:
``` python
# Warmup 1a:
```
%% Output
<class 'dict'>
%% Cell type:code id: tags:
``` python
# Warmup 1b: How do you make an empty set?
thing2 = set()
print(type(thing2))
```
%% Output
<class 'set'>
%% Cell type:code id: tags:
``` python
# Warmup 1c:
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:markdown id: tags:
## October 25: Objects and Tuples
Learning Objectives:
- Explain the difference between objects vs references, and stack vs heap.
- Determine the side effects that occur when modifying parameters.
- Use tuples to store immutable sequences of values.
- Use namedtuple (immutable) to store user-defined data objects.
%% Cell type:code id: tags:
``` python
```
%% Cell type:markdown id: tags:
### Explain the difference between objects vs references, and stack vs heap.
- check out the slides starting at slide ____
- try some of that code in Python Tutor
%% Cell type:markdown id: tags:
### Determine the side effects that occur when modifying parameters.
%% Cell type:code id: tags:
``` python
# example 5a: try this in Python tutor
def f(x):
x *= 3
print("f:", x)
num = 10
f(num)
print("after:", num)
# takeaway: what happens when a parameter is reassigned?
```
%% Output
f: 30
after: 10
%% Cell type:code id: tags:
``` python
# example 5b: try in Python Tutor
def f(items):
items.append("!!!")
print("f:", items)
words = ['hello', 'world']
f(words)
print("after:", words)
# takeaway: what happens when a list parameter is mutated ?
```
%% Output
f: ['hello', 'world', '!!!']
after: ['hello', 'world', '!!!']
%% Cell type:code id: tags:
``` python
# example 5c: try in Python Tutor
def f(items):
items = items + ["!!!"]
print("f:", items)
words = ['hello', 'world']
f(words)
print("after:", words)
# takeaway: what happens when a list parameter is reassigned ?
```
%% Output
f: ['hello', 'world', '!!!']
after: ['hello', 'world']
%% Cell type:code id: tags:
``` python
# example 5d: try in Python Tutor
def first(items):
return items[0]
def smallest(items):
items.sort()
return items[0]
numbers = [4,5,3,2,1]
print("first:", first(numbers))
print("smallest:", smallest(numbers))
print("first:", first(numbers))
# takeaway: what happens when a list parameter is sorted "in place" using .sort() ?
```
%% Output
first: 4
smallest: 1
first: 1
%% Cell type:code id: tags:
``` python
# example 5e: try in Python Tutor
def first(items):
return items[0]
def smallest(items):
items = sorted(items)
return items[0]
numbers = [4,5,3,2,1]
print("first:", first(numbers))
print("smallest:", smallest(numbers))
print("first:", first(numbers))
# takeaway: what happens when a list parameter is sorted using sorted()?
```
%% Output
first: 4
smallest: 1
first: 4
%% Cell type:markdown id: tags:
### In summary, write one good thing and bad thing about lists being mutable
%% Cell type:code id: tags:
``` python
# Good thing:
#
```
%% Cell type:code id: tags:
``` python
# Bad thing:
#
```
%% Cell type:markdown id: tags:
### Use tuples to store immutable sequences of values.
Check out the slides about tuples
%% Cell type:code id: tags:
``` python
# Tuples are like lists BUT are IMMUTABLE
# practice with tuples
scores = [32, 55, 72, 91] # a list is mutable
coordinates = (-3, 4, 7) # a tuple is not mutable
# show that scores is mutable
scores[-1] = 100
print(scores)
coordinates = (5, 77, -3) #re-assignment is OK
# show that tuples are immutable
#coordinates[-1] = 100. #tuple not mutable
#print(coordinates)
scores_tuple = tuple(scores) # you can convert a list into a tuple
print(scores_tuple)
# Question: Can tuples be sorted?
# Discuss with your neighbor
# coordinates.sort() # tuples are immutable
new_tuple = sorted(coordinates) # sorted makes a new object
# Takeaway: Write a note to yourself about tuples
```
%% Output
[32, 55, 72, 100]
(32, 55, 72, 100)
%% Cell type:code id: tags:
``` python
# reference: https://www.w3schools.com/python/python_tuples.asp
```
%% Cell type:code id: tags:
``` python
# Why use tuples?
# keys in dictionaries must be immutable types
# some data never changes : GPS coordinates
# Fails with TypeError
buildings = {
[0,0]: "Comp Sci",
[0,2]: "Psychology",
[4,0]: "Noland",
[1,8]: "Van Vleck" }
```
%% Output
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-8-266ce4d9d9c7> in <module>
4
5 # Fails with TypeError
----> 6 buildings = {
7 [0,0]: "Comp Sci",
8 [0,2]: "Psychology",
TypeError: unhashable type: 'list'
%% Cell type:code id: tags:
``` python
# Works with tuple as keys
buildings = {
(0,0): "Comp Sci",
(0,2): "Psychology",
(4,0): "Noland",
(1,8): "Van Vleck" }
# find the name of the building at coordinate (4,0)
```
%% Output
{(0, 0): 'Comp Sci',
(0, 2): 'Psychology',
(4, 0): 'Noland',
(1, 8): 'Van Vleck'}
%% Cell type:markdown id: tags:
### 21.3 Use namedtuple (immutable) to store user-defined data objects.
- namedtuple is useful for creating well-defined objects
- namedtuple is like a mix of tuples and dictionaries
- let's look at the slides
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
# A namedtuple is like its own kind of type!
# its a Python convention to use a Capital letter when naming a namedtuple
# define a namedtuple called Person
Person = namedtuple("Person", ["fname", "lname", "age"])
# make a single person....pls don't name it person !!
p1 = Person("Bucky", "Badger", 124)
print(p1.age)
# right here, add another Person by using keyword arguments
person2 = Person(age=13, lname="Kuemmel", fname = "Stevie")
# add this person to your list....
people.append(person2)
```
%% Output
124
Hello Alice Anderson
[Person(fname='Alice', lname='Anderson', age=30), Person(fname='Bob', lname='Baker', age=31), Person(fname='Celia', lname='Answer', age=21), Person(fname='Marcus', lname='Carlson', age=33), Person(fname='Stevie', lname='Kuemmel', age=13)]
Hello Alice Anderson
Hello Bob Baker
Hello Celia Answer
Hello Marcus Carlson
Hello Stevie Kuemmel
%% Cell type:code id: tags:
``` python
# make a list of Persons
people=[
Person("Alice", "Anderson", 30), # positional arguments
Person("Bob", "Baker", 31),
# add two more Persons to people
Person("Celia", "Answer", 21),
Person("Marcus", "Carlson", 33)
]
person0 = people[0]
print("Hello " + person0.fname + " " + person0.lname)
```
%% Cell type:code id: tags:
``` python
# print out people
print(people)
for p in people:
print("Hello " + p.fname + " " + p.lname)
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
# Namedtuples have a deeper significance....the namedtuples we create are their own type
```
%% Cell type:markdown id: tags:
![namedtuple.png](attachment:namedtuple.png)
%% Cell type:code id: tags:
``` python
# write a function to find the average age of the Persons in people
# Practice
def avg_age(p_list):
# assume p_list is a list of Persons
sum = 0
return sum
avg_age(people)
```
%% Output
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-11-29e651cafe44> in <module>
8 return sum
9
---> 10 avg_age(people)
NameError: name 'people' is not defined
%% Cell type:code id: tags:
``` python
# how can you demonstrate that namedtuples are immutable
# but lists of namedtuples are mutable
# Practice
```
%% Output
15
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
%% Cell type:code id: tags:
``` python
```
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