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

Update f22/andy_lec_notes/lec21_Oct26_Copying/lec21_copying_template.ipynb

parent b5909b67
No related branches found
No related tags found
No related merge requests found
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
import copy # we are going to learn about this module today import copy # we are going to learn about this module today
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Warmup ## Warmup
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
college_dict = { # Warmup 1: determine the key that has the highest value in a dict
"UW": {'name': "University of Wisconsin", 'type':'public', 'year': 1850, 'enrollment': 35474 },
"MI": {'name': "University of Michigan", 'type':'public', 'year': 1817, 'enrollment': 44718 },
"MU": {'name': "Marquette University", 'type':'private', 'year': 1881, 'enrollment': 11294 },
"EDG": {'name': "Edgewood College", 'type':'private', 'year': 1927, 'enrollment': 2650 },
}
```
%% Cell type:code id: tags:
``` python # which dog is the oldest?
#Warmup 1: What is the name of the university that is the oldest? dog_dict = {"Miles": 2, "Gertie": 4, "Sammy": 11, "Fido": 3, "Jordy": 5}
oldest_dog = None
max_age = 0
oldest_name = None
year_founded = None
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
#Warmup 2: using one dict to make a new dict #Warmup 2: Which dog is the oldest?
dog_list = [ {'id': 34523, 'name': "Miles", 'age': 2},
# let's make a new dictionary of the total enrollment by type {'id': 22334, 'name': "Gertie", 'age': 4},
# key is the type, value is the total enrollment for that type {'id': 87654, 'name': "Fido", 'age': 3'} ]
oldest_dog = None
enrollment_by_type_dict = {} max_age = 0
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
# Lecture 21: Reference Copy, Copy, Deep Copy # Lecture 21: Reference Copy, Copy, Deep Copy
Learning Objectives: Learning Objectives:
- Correctly predict the output of code that uses reference variable mutation and reassignment. - Correctly predict the output of code that uses reference variable mutation and reassignment.
- Compare and contrast the 3 levels of copying: - Compare and contrast the 3 levels of copying:
- reference copy - reference copy
- shallow copy(copy.copy) - shallow copy(copy.copy)
- deep copy (copy.deepcopy) - deep copy (copy.deepcopy)
- Write code that copies a data structure at the appropriate level for a given use case. - Write code that copies a data structure at the appropriate level for a given use case.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Correctly predict the output of code that uses reference variable mutation and reassignment. ## Correctly predict the output of code that uses reference variable mutation and reassignment.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# Example 1...predict the answer, uncomment the print statement, see if you were correct # Example 1...predict the answer, uncomment the print statement, see if you were correct
# for extra understanding, go to Python tutor # for extra understanding, go to Python tutor
dict1 = {} dict1 = {}
dict2 = {} dict2 = {}
#dict2 = dict1 # reference variable reassignment #dict2 = dict1 # reference variable reassignment
#dict1["MI"] = "Ann Arbor" #dict1["MI"] = "Ann Arbor"
#dict2["WI"] = "Madison" #dict2["WI"] = "Madison"
print(dict1, dict2) print(dict1, dict2)
``` ```
%% Output %% Output
{'MI': 'Ann Arbor'} {} {'MI': 'Ann Arbor'} {}
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Compare and contrast the 3 levels of copying: ## Compare and contrast the 3 levels of copying:
- reference copy - reference copy
- shallow copy (copy.copy) # one level of object depth - shallow copy (copy.copy) # one level of object depth
- deep copy (copy.deepcopy) # all levels of object depth - deep copy (copy.deepcopy) # all levels of object depth
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
![three%20levels%20copy.png](attachment:three%20levels%20copy.png) ![three%20levels%20copy.png](attachment:three%20levels%20copy.png)
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# Run this in Python Tutor, and uncomment one option at a time. # Run this in Python Tutor, and uncomment one option at a time.
import copy import copy
x =[ x =[
{"name":"A", "score":88}, {"name":"A", "score":88},
{"name":"B", "score":111}, {"name":"B", "score":111},
{"name":"C", "score":100}] {"name":"C", "score":100}]
#y = x # reference copy #y = x # reference copy
#y[0]['name'] = "Andy" #y[0]['name'] = "Andy"
#y = copy.copy(x) # shallow copy...copies the first level #y = copy.copy(x) # shallow copy...copies the first level
#y[1]['name'] = "Bianca" #y[1]['name'] = "Bianca"
#y = copy.deepcopy(x) # deep copy...copies down to every level #y = copy.deepcopy(x) # deep copy...copies down to every level
#y[2]['name'] = "Chris" #y[2]['name'] = "Chris"
# takeway: Write a note to yourself # takeway: Write a note to yourself
# #
# #
# #
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
## Write code that copies a data structure at the appropriate level for a given use case. ## Write code that copies a data structure at the appropriate level for a given use case.
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
![player_score.png](attachment:player_score.png) ![player_score.png](attachment:player_score.png)
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
![use%20case%201.png](attachment:use%20case%201.png) ![use%20case%201.png](attachment:use%20case%201.png)
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# Example 4a: Given this playlist # Example 4a: Given this playlist
player_scores = [ player_scores = [
{"name":"Anna", "score":88}, {"name":"Anna", "score":88},
{"name":"Bianca", "score":111}, {"name":"Bianca", "score":111},
{"name":"Chris", "score":100} {"name":"Chris", "score":100}
] ]
# a.) write a function that finds the name of the person # a.) write a function that finds the name of the person
# with the highest score score in a list of dicts with keys 'name' , 'score' # with the highest score score in a list of dicts with keys 'name' , 'score'
def max_score(score_list): def max_score(score_list):
best_person = None best_person = None
high_score = None high_score = None
return best_person return best_person
#print(player_scores) #print(player_scores)
print(max_score(player_scores)) print(max_score(player_scores))
#print(player_scores) #print(player_scores)
# after you write this code, run it in Python Tutor # after you write this code, run it in Python Tutor
``` ```
%% Output %% Output
Bianca Bianca
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# Use Case 2 below # Use Case 2 below
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
![ex%202.png](attachment:ex%202.png) ![ex%202.png](attachment:ex%202.png)
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# Example 4b.) use a shallow copy to sort each list of scores # Example 4b.) use a shallow copy to sort each list of scores
player_scores = [ player_scores = [
{"name":"Anna", "scores":[23, 18, 11, 17, 6]}, {"name":"Anna", "scores":[23, 18, 11, 17, 6]},
{"name":"Bianca", "scores":[11, 21, 9, 4, 10]}, {"name":"Bianca", "scores":[11, 21, 9, 4, 10]},
{"name":"Chris", "scores":[12, 10, 3, 8, 7]} {"name":"Chris", "scores":[12, 10, 3, 8, 7]}
] ]
player_scores_copy = copy.copy(player_scores) # makes a shallow copy player_scores_copy = copy.copy(player_scores) # makes a shallow copy
# iterate through the list player_scores_copy and sort each list # iterate through the list player_scores_copy and sort each list
print(player_scores) # should be unchanged print(player_scores) # should be unchanged
print(player_scores_copy) print(player_scores_copy)
``` ```
%% Output %% Output
<class 'dict'> <class 'dict'>
<class 'dict'> <class 'dict'>
<class 'dict'> <class 'dict'>
[{'name': 'Anna', 'scores': [11, 17, 18, 23]}, {'name': 'Bianca', 'scores': [4, 9, 11, 21]}, {'name': 'Carl', 'scores': [3, 8, 10, 12]}] [{'name': 'Anna', 'scores': [11, 17, 18, 23]}, {'name': 'Bianca', 'scores': [4, 9, 11, 21]}, {'name': 'Carl', 'scores': [3, 8, 10, 12]}]
[{'name': 'Anna', 'scores': [11, 17, 18, 23]}, {'name': 'Bianca', 'scores': [4, 9, 11, 21]}, {'name': 'Carl', 'scores': [3, 8, 10, 12]}] [{'name': 'Anna', 'scores': [11, 17, 18, 23]}, {'name': 'Bianca', 'scores': [4, 9, 11, 21]}, {'name': 'Carl', 'scores': [3, 8, 10, 12]}]
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# Use Case 3 below # Use Case 3 below
``` ```
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
![ex%203.png](attachment:ex%203.png) ![ex%203.png](attachment:ex%203.png)
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
#Example 4c.) make a deep copy as a backup, then change the original #Example 4c.) make a deep copy as a backup, then change the original
player_scores= [ player_scores= [
{"name":"Anna", "score":88}, {"name":"Anna", "score":88},
{"name":"Bianca", "score":111}, {"name":"Bianca", "score":111},
{"name":"Chris", "score":100} {"name":"Chris", "score":100}
] ]
players_before = copy.deepcopy(player_scores) players_before = copy.deepcopy(player_scores)
# change someone's score here # change someone's score here
print(players_before) print(players_before)
print('after changes:') print('after changes:')
print(player_scores) print(player_scores)
answer = input("enter y to keep changes: ") answer = input("enter y to keep changes: ")
if answer != 'y': if answer != 'y':
player_scores = players_before player_scores = players_before
print(players_before) print(players_before)
print('after changes:') print('after changes:')
print(player_scores) print(player_scores)
# after you write this code, run it in Python Tutor # after you write this code, run it in Python Tutor
``` ```
%% Output %% Output
[{'name': 'Anna', 'score': 88}, {'name': 'Bianca', 'score': 111}, {'name': 'Carl', 'score': 100}] [{'name': 'Anna', 'score': 88}, {'name': 'Bianca', 'score': 111}, {'name': 'Carl', 'score': 100}]
after changes: after changes:
[{'name': 'Anna', 'score': 88}, {'name': 'Bianca', 'score': 120}, {'name': 'Carl', 'score': 100}] [{'name': 'Anna', 'score': 88}, {'name': 'Bianca', 'score': 120}, {'name': 'Carl', 'score': 100}]
enter y to keep changes: n enter y to keep changes: n
[{'name': 'Anna', 'score': 88}, {'name': 'Bianca', 'score': 111}, {'name': 'Carl', 'score': 100}] [{'name': 'Anna', 'score': 88}, {'name': 'Bianca', 'score': 111}, {'name': 'Carl', 'score': 100}]
after changes: after changes:
[{'name': 'Anna', 'score': 88}, {'name': 'Bianca', 'score': 111}, {'name': 'Carl', 'score': 100}] [{'name': 'Anna', 'score': 88}, {'name': 'Bianca', 'score': 111}, {'name': 'Carl', 'score': 100}]
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# Note: Deepcopy is also known as a Recursive copy. # Note: Deepcopy is also known as a Recursive copy.
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# Think about it. When you slice a list fully, using [:], what kind of copy is this? # Think about it. When you slice a list fully, using [:], what kind of copy is this?
favorites = [ 17, ['Miles', 'Gertie'], {'a': 65, 'b': 66, 'c': 67}, True] favorites = [ 17, ['Miles', 'Gertie'], {'a': 65, 'b': 66, 'c': 67}, True]
sliced = favorites [:] sliced = favorites [:]
# try in Python Tutor # try in Python Tutor
# your answer: # your answer:
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
# Do Worksheet for today (good quiz practice) # Do Worksheet for today (good quiz practice)
# Answers will be posted on later today to the same place you found this Notebook file. # Answers will be posted on later today to the same place you found this Notebook file.
``` ```
......
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