Skip to content
Snippets Groups Projects
Commit d75b2fac authored by LOUIS TYRRELL OLIPHANT's avatar LOUIS TYRRELL OLIPHANT
Browse files

finished lec 24 comprehensions

parent e7737d2a
No related branches found
No related tags found
No related merge requests found
%% Cell type:markdown id: tags:
## Warmup
%% Cell type:code id: tags:
``` python
# Warmup 1a: Sort this list by the length of each word using key=get_fruit_len
fruits = ["blackberry", "apple", "banana", "fig", "blueberry", "strawberry"]
def get_fruit_len(f):
pass
# TODO Sort the list of fruits
```
%% Cell type:code id: tags:
``` python
# Warmup 1b: Sort this list by the length of each word using a lambda
fruits = ["blackberry", "apple", "banana", "fig", "blueberry", "strawberry"]
```
%% Cell type:code id: tags:
``` python
# Warmup 2: Define: What is a lambda function?
```
%% Cell type:code id: tags:
``` python
# Warmup 3: Sort this dictionary by their total enrollment
enrollments = { "Wisconsin": 45540,
"Michigan": 47907,
"Illinois": 52331,
"Iowa": 30448,
"Minnesota": 52017,
"Ohio State": 61369,
"Northwestern": 22316}
```
%% Cell type:code id: tags:
``` python
# Warmup 4: Sort this list of dictionaries by 'name'
volunteers = [ {"name": "Sky", "hours": 53},
{"name":"Patrice", "hours": 72},
{"name":"Gabriella", "hours": 45},
{"name": "Jade", "hours": 62} ]
```
%% Cell type:code id: tags:
``` python
# Warmup 5: Sort this dictionary of lists by the length of the list
cities_by_county = {"Dane": ["Madison", "Sun Prairie", "Middleton", "Waunakee"],
"Milwaukee": ["Milwaukee", "West Allis", "Wauwatosa"],
"Rock": ["Janesville", "Beloit"],
"Waukesha": ["Brookfield"]}
```
%% Cell type:code id: tags:
``` python
# Warmup 6: Create a list of all fruits that contain 'berry'
fruits = ["blackberry", "apple", "banana", "fig", "blueberry", "strawberry"]
```
%% Cell type:markdown id: tags:
# Iterators and Comprehensions
## Read
- [Downey Ch 19.2](https://greenteapress.com/thinkpython2/html/thinkpython2020.html) and [12.3](https://greenteapress.com/thinkpython2/html/thinkpython2013.html)
## Learning Objectives
- Create list and dictionary comprehensions
- Use the correct vocabulary to describe iteration
- iterable, sequence, iterator
- Determine if an object is an iterable, or if it is an iterator
- try to use iter() to determine if an object is an iterable
- try to use next() to determine if an object is an iterator
- Use iterator/iterable language to open and process files
- Use the alterate syntax to handle if/else conditions in comprehensions
%% Cell type:markdown id: tags:
## List Comprehensions
List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list.
```python
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []
for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist)
```
Using **list comprehensions** you can do all of this work in one line of code.
```python
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits if "a" in x]
print(newlist)
```
the general syntax is:
```
newlist = [expression for item in iterable if condition]
```
Let's try putting different things for `expression` and `condition` to understand what they control. Let's first look at the `condition`.
%% Cell type:code id: tags:
``` python
# Do we have a shorter way to complete Warmup 6?
# https://en.wikipedia.org/wiki/Code_golf
# Yes! Using List Comprehensions -- Create a list of all fruits that contain 'berry'
fruits = ["blackberry", "apple", "banana", "fig", "blueberry", "strawberry"]
[x for x in fruits if 'berry' in x]
```
%% Cell type:markdown id: tags:
#### You Try It
%% Cell type:code id: tags:
``` python
# All fruits that start with the letter 'b'
# Get all fruits that start with the letter 'b'
```
%% Cell type:markdown id: tags:
Now let's try different things for the `expression`.
%% Cell type:code id: tags:
``` python
# All fruits with short names
# Get the first three letters of all fruits
[x[:3] for x in fruits]
```
%% Cell type:markdown id: tags:
#### You Try It
%% Cell type:code id: tags:
``` python
# The length of every fruit name
```
%% Cell type:markdown id: tags:
### More List Comprehensions
%% Cell type:code id: tags:
``` python
# Convert these Fahrenheit temps to an int in Celsius using C = 5/9 * (F-32)
temps = [32, 45, 90, 212]
# First, write using a traditional for loop...
```
%% Cell type:code id: tags:
``` python
# Then, try writing it as a list comprehension!
```
%% Cell type:code id: tags:
``` python
# What if temps were strings?
temps = ["32", "", "45", "90", "212"]
```
%% Cell type:markdown id: tags:
### Even More List Comprehensions
Now try working with a list of dictionaries to create a new list. These may require varying both the `expression` and the `condition`.
%% Cell type:code id: tags:
``` python
# What ways could we filter this list of volunteers?
volunteers = [ {"name": "Sky", "hours": 53},
{"name": "Patrice", "hours": 72},
{"name": "Gabriella", "hours": 45},
{"name": "Jade", "hours": 62}
]
```
%% Cell type:code id: tags:
``` python
# names of those that have volunteered at least 60 hours
```
%% Cell type:code id: tags:
``` python
# names of those with short names
```
%% Cell type:code id: tags:
``` python
# What if we wanted to keep the name and hours?
```
%% Cell type:markdown id: tags:
### Dictionary Comprehensions
Same thing as a list comprehension, but with a key *and* value!
## Dictionary Comprehensions
A dictionary comprehension creates a dictionary from a list using similar syntax as a list comprehension, but with a key *and* value!
```
{key:value for item in iterable if condition}
```
%% Cell type:code id: tags:
``` python
# Generate a dictionary of numbers and their squares! e.g. {1: 1, 2: 4, 3: 9, 4: 16, ...}
nums = [1, 2, 3, 4, 5, 6, 7]
square_mapping_dict = ...
square_mapping_dict = {x:x*x for x in nums}
square_mapping_dict
```
%% Cell type:markdown id: tags:
### You Try It
Create a dictionary where the key is the fruit name and the value is the fruit length.
%% Cell type:code id: tags:
``` python
fruits = ["blackberry", "apple", "banana", "fig", "blueberry", "strawberry"]
```
%% Cell type:markdown id: tags:
### Using the dictionaries `items()` method
Recall the `.items()` method converts key,value pairs in a dictionary to a list-like structure of (key,value) tuples. You can then use this with comprehensions.
%% Cell type:code id: tags:
``` python
# What ways could we filter this dictionary of people's scores?
scores_dict = {"Bob": [18, 72, 83],
"Cindy" : [27, 11, 55, 73, 87],
"Alice": [16, 33, 42, 89, 90],
"Meena": [39, 93, 9, 3, 55, 72, 19]}
# A dictionary of how many scores each player has
# A dictionary of everyone's highest score
# A dictionary of everyone's average score
# ...
scores_dict.items()
```
%% Cell type:code id: tags:
``` python
# Tip: We can use "tuple unpacking" in our for loop!
# An old fashioned for loop...
# Here is how it can be done using a traditional for loop
new_scores_dict = {}
for (player, scores) in scores_dict.items():
new_scores_dict[player] = len(scores)
new_scores_dict
```
%% Cell type:code id: tags:
``` python
# A dictionary of how many scores each player has
# Here is how it could be done using a comprehension
new_scores_dict = {x[0]:len(x[1]) for x in scores_dict.items()}
new_scores_dict
```
%% Cell type:markdown id: tags:
#### You Try It
Create the dictionaries described below using comprehensions.
%% Cell type:code id: tags:
``` python
# A dictionary of everyone's highest score
```
%% Cell type:code id: tags:
``` python
# A dictionary of everyone's average score
```
%% Cell type:code id: tags:
``` python
# Challenge: A sorted dictionary of everyone's average score.
# Hint: Convert the above dictionary to a list of tuples,
# sort based on the score, and turn back into a dict.
```
%% Cell type:markdown id: tags:
### The Syntax of Comprehensions
### The Syntax and Alternate Syntax of Comprehensions
There is a second syntax for creating a comprehension that can handle values for the `if` and `else`
portion of a conditional.
%% Cell type:markdown id: tags:
![comprehensions.png](attachment:comprehensions.png)
%% Cell type:code id: tags:
``` python
scores = [87, 45, 67, 76, 88, 91, 71]
['pass' if x >= 60 else 'fail' for x in scores]
```
%% Cell type:markdown id: tags:
#### You Try It
Create a list of boolean values using scores indicating `True` if the score is even and `False` otherwise.
%% Cell type:code id: tags:
``` python
```
%% Cell type:markdown id: tags:
For more reference, visit...
https://www.w3schools.com/python/python_lists_comprehension.asp
https://www.datacamp.com/community/tutorials/python-dictionary-comprehension
%% Cell type:markdown id: tags:
### Challenge: Recursion, Lambdas, and Comprehensions Together!
Sort the family tree as a list of people from youngest to oldest.
Sort the `family_tree` to create a list of dictionaries representing people from youngest to oldest.
%% Cell type:markdown id: tags:
Expected Output:
```
[{'name': 'Jayden', 'age': 1},
{'name': 'Penelope', 'age': 24},
{'name': 'Skyla', 'age': 46},
{'name': 'Julia', 'age': 66},
{'name': 'Irine', 'age': 92},
{'name': 'Dot', 'age': 111}]
```
%% Cell type:code id: tags:
``` python
family_tree = {
"name": "Jayden",
"age": 1,
"mother": {
"name": "Penelope",
"age": 24,
"mother": {
"name": "Skyla",
"age": 46,
"mother": {
"name": "Julia",
"age": 66,
"mother": {
"name": "Irine",
"age": 92,
"mother": {
"name": "Dot",
"age": 111,
}
}
}
}
}
}
def get_person_info(person):
"""
person is a dictionary of key:value pairs where the keys are different attributes about the person (including mother)
person is a dictionary of key:value pairs where the keys are different attributes about
the person (including mother).
return a dictionary of the same key:value pairs without the mother key
"""
pass # hint: try to use a dictionary comprehension
def get_people(person):
"""
person is a dictionary of key:value pairs where the keys are different attributes about the person (including mother)
return a list of dictionaries where each dictionary are the key:value pairs for a person without the mother key
person is a dictionary of key:value pairs where the keys are different attributes about
the person (including mother)
return a list of dictionaries where each dictionary are the key:value pairs for a person
without the mother key
"""
person_info = get_person_info(person)
if ???: # base case
return [person_info]
else: # recursive case
current_mother = person['mother']
return ???
family_list = get_people(family_tree)
??? # hint: sort the family_list by age using a lambda function
```
......
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