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

added Louis's Lec 12 notebooks

parent e633f872
No related branches found
No related tags found
No related merge requests found
%% Cell type:code id: tags:
``` python
# Warmup 1: Complete the code to print a treasure map where an X is placed
# treasure_row, treasure_col (starting from 0)
def print_treasure_map(symbol='-', height=4, width=4, treasure_row=2, treasure_col=2):
i = 0
while i < height:
j = 0
while j < width:
if i == treasure_row and j == treasure_col:
print('X', end="")
else:
print(symbol, end="")
j += 1
print()
i += 1
print_treasure_map()
#print_treasure_map(width=10, height=10)
#print_treasure_map('#', 7, 4, treasure_row=0, treasure_col=1)
#print_treasure_map('.', 5, 8, 3, 6)
```
%% Output
----
----
--X-
----
%% Cell type:code id: tags:
``` python
# Warmup 2: Write a function that prints the factorial of parameter num
def do_factorial(num):
i = 1
factorial = 1
while i <= num:
factorial = factorial * i
i += 1
return factorial
do_factorial(5)
```
%% Output
120
%% Cell type:markdown id: tags:
# CS220: Lecture 12
## Learning Objectives
After this lecture you will be able to...
- Iterate through a dataset using for idx in range(project.count())
- Compute the frequency of data that meets a certain criteria
- Find the maximum or minimum value of a numeric column in a dataset
- Use break and continue in for loops when processing a dataset
- Handle missing numeric values when computing a maximum/minimum
- Use the index of a maximum or minimum to access other information about that data item
%% Cell type:code id: tags:
``` python
import project
```
%% Cell type:code id: tags:
``` python
help(project)
```
%% Output
Help on module project:
NAME
project
FUNCTIONS
__init__()
count()
This function will return the number of records in the dataset
get_age(idx)
get_age(idx) returns the age of the student in row idx
get_cats_or_dogs(idx)
get_cats_or_dogs(idx) returns whether student in row idx likes cats or dogs
get_lecture(idx)
get_lecture(idx) returns the lecture of the student in row idx
get_other_majors(idx)
get_other_majors(idx) returns the secondary major of the student in row idx
get_pizza_topping(idx)
get_pizza_topping(idx) returns the preferred pizza toppings of the student in row idx
get_primary_major(idx)
get_primary_major(idx) returns the primary major of the student in row idx
get_procrastinator(idx)
get_procrastinator(idx) returns whether student in row idx is a procrastinator
get_runner(idx)
get_runner(idx) returns whether student in row idx is a runner
get_section(idx)
get_lecture(idx) returns the section of the student in row idx
get_sleep_habit(idx)
get_sleep_habit(idx) returns the sleep habit of the student in row idx
get_song(idx)
get_procrastinator(idx) returns the student in row idx favorite song
get_zip_code(idx)
get_zip_code(idx) returns the residential zip code of the student in row idx
DATA
__student__ = [{'Age': '19', 'Cats or dogs': 'cat', 'Latitude': '44.25...
FILE
/home/oliphant/OneDrive/courses/cs220/repositories/cs220-lecture-material/s24/Louis_Lecture_Notes/12_Iteration_Practice/project.py
%% Cell type:code id: tags:
``` python
# Get the total # of responses
project.count()
```
%% Output
1019
%% Cell type:code id: tags:
``` python
# Get the first student's primary major.
# With indices, we always start from 0!
project.get_primary_major(0)
```
%% Output
'Other (please provide details below).'
%% Cell type:code id: tags:
``` python
# Example 1: Print and Break
for i in range(project.count()):
print (i, project.get_primary_major(i))
if i == 10:
break
```
%% Output
0 Other (please provide details below).
1 Engineering: Biomedical
2 Computer Science
3 Engineering: Other
4 Data Science
5 Engineering: Biomedical
6 Mathematics/AMEP
7 Engineering: Mechanical
8 Other (please provide details below).
9 Other (please provide details below).
10 Business: Information Systems
%% Cell type:code id: tags:
``` python
# TODO: Write the same code as above using a while loop!
i = 0
while i <= 10:
print(i, project.get_primary_major(i))
i += 1
```
%% Output
0 Other (please provide details below).
1 Engineering: Biomedical
2 Computer Science
3 Engineering: Other
4 Data Science
5 Engineering: Biomedical
6 Mathematics/AMEP
7 Engineering: Mechanical
8 Other (please provide details below).
9 Other (please provide details below).
10 Business: Information Systems
%% Cell type:code id: tags:
``` python
# Example 2: How many students are not in Computer Science?
non_cs = 0
for i in range(project.count()):
major = project.get_primary_major(i)
if major == "Computer Science":
continue
non_cs += 1
print(non_cs, "out of", project.count(), "are non-cs!")
```
%% Output
942 out of 1019 are non-cs!
%% Cell type:code id: tags:
``` python
# TODO: How many students are in Data Science or Statistics?
# BONUS: Can you express this as a percentage?
# BONUS+: ...rounded to 2 decimal places?
num_stats_or_ds = 0
for i in range(project.count()):
major = project.get_primary_major(i)
if major == "Data Science" or major == "Statistics":
num_stats_or_ds += 1
print(num_stats_or_ds)
percent_dsstats = (num_stats_or_ds / project.count()) * 100
print(round(percent_dsstats, 2))
```
%% Output
200
19.63
%% Cell type:code id: tags:
``` python
help(project)
```
%% Output
Help on module project:
NAME
project
FUNCTIONS
__init__()
count()
This function will return the number of records in the dataset
get_age(idx)
get_age(idx) returns the age of the student in row idx
get_cats_or_dogs(idx)
get_cats_or_dogs(idx) returns whether student in row idx likes cats or dogs
get_lecture(idx)
get_lecture(idx) returns the lecture of the student in row idx
get_other_majors(idx)
get_other_majors(idx) returns the secondary major of the student in row idx
get_pizza_topping(idx)
get_pizza_topping(idx) returns the preferred pizza toppings of the student in row idx
get_primary_major(idx)
get_primary_major(idx) returns the primary major of the student in row idx
get_procrastinator(idx)
get_procrastinator(idx) returns whether student in row idx is a procrastinator
get_runner(idx)
get_runner(idx) returns whether student in row idx is a runner
get_section(idx)
get_lecture(idx) returns the section of the student in row idx
get_sleep_habit(idx)
get_sleep_habit(idx) returns the sleep habit of the student in row idx
get_song(idx)
get_procrastinator(idx) returns the student in row idx favorite song
get_zip_code(idx)
get_zip_code(idx) returns the residential zip code of the student in row idx
DATA
__student__ = [{'Age': '19', 'Cats or dogs': 'cat', 'Latitude': '44.25...
FILE
/home/oliphant/OneDrive/courses/cs220/repositories/cs220-lecture-material/s24/Louis_Lecture_Notes/12_Iteration_Practice/project.py
%% Cell type:code id: tags:
``` python
# max = 0 # don't use built-in function names as variables
# DATA FIX: In the CSV file, change the student's age from "Senior" to 22.
max_age = 0
for i in range(project.count()):
student_age = project.get_age(i)
if student_age == '':
continue
student_age = int(student_age)
if student_age > max_age:
max_age = student_age
print("The oldest student is", max_age)
# HINT: Did everyone fill out an age?
# HINT: We may have to change the data and run project.reload()
```
%% Output
The oldest student is 40
%% Cell type:code id: tags:
``` python
# TODO: What is the age of the youngest student?
# max = 0 # don't use built-in function names as variables
min_age = int(project.get_age(0))
for i in range(project.count()):
student_age = project.get_age(i)
if student_age == '':
continue
student_age = int(student_age)
if student_age < min_age:
min_age = student_age
print("The youngest student is", min_age)
```
%% Output
The youngest student is 17
%% Cell type:code id: tags:
``` python
# Example 5: How many early birds are there below the age of 21?
early_birds = 0
total_students = 0
for i in range(project.count()):
sleep_habit = project.get_sleep_habit(i)
age = project.get_age(i)
if age != "":
age = int(age)
if age < 21 : # TODO Complete this condition!
total_students += 1
if sleep_habit == "early bird":
early_birds += 1
print("There are", early_birds, "early birds below the age of 21.")
print("There are", total_students, "total students below the age of 21.")
```
%% Output
There are 190 early birds below the age of 21.
There are 791 total students below the age of 21.
%% Cell type:code id: tags:
``` python
# TODO: What percentage of 20-year-olds are early birds?
# BOUNUS: How can we generalize our code to 'What percentage of x-year-olds are early birds?'
# Example 5: How many early birds are there below the age of 21?
def print_early_birds(target_age):
early_birds = 0
total_students = 0
for i in range(project.count()):
sleep_habit = project.get_sleep_habit(i)
age = project.get_age(i)
if age != "":
age = int(age)
if age == target_age:
total_students += 1
if sleep_habit == "early bird":
early_birds += 1
print("There are", early_birds, "early birds that are 20.")
print("There are", total_students, "total students that are 20.")
per_early = round((early_birds / total_students) * 100, 2)
print(str(per_early) + "% of " + str(target_age) + " year olds are early birds")
print_early_birds(20)
```
%% Output
There are 47 early birds that are 20.
There are 165 total students that are 20.
28.48% of 20 year olds are early birds
%% Cell type:code id: tags:
``` python
# Other tasks for you to try...
# - What is the average age of the class?
# - What is the class's favorite pizza topping?
# - What is the most popular major?
# - For all students that have another major, print out what it is.
# - What zip code do the majority of pineapple-eating night owls live in?
```
%% Cell type:code id: tags:
``` python
# Warmup 1: Complete the code to print a treasure map where an X is placed
# treasure_row, treasure_col (starting from 0)
def print_treasure_map(symbol='-', height=4, width=4, treasure_row=2, treasure_col=2):
i = 0
while ???: # TODO: Complete the loop condition for printing out each row.
j = 0
while j < width:
if ???: # TODO: Complete the if condition for checking if we print an X or the symbol.
print('X', end="")
else:
print(symbol, end="")
j += ??? # TODO: Complete the statement so we do not run into an infinite loop.
print()
i += 1
print_treasure_map()
print_treasure_map(width=10, height=10)
print_treasure_map('#', 7, 4, treasure_row=0, treasure_col=1)
print_treasure_map('.', 5, 8, 3, 6)
```
%% Cell type:code id: tags:
``` python
# Warmup 2: We will do this one together
# Write a function that prints the factorial of parameter num
# Recall that the factorial of a number n is n * (n-1) * (n-2) * (n-3) ... * 3 * 2 * 1
def do_factorial(num):
pass
```
%% Cell type:markdown id: tags:
# CS220: Lecture 12
## Learning Objectives
After this lecture you will be able to...
- Iterate using `for x in range()` over lists and strings
- Iterate through a dataset using `for idx in range(project.count())`
- Compute the frequency of data that meets a certain criteria
- Find the maximum or minimum value of a numeric column in a dataset
- Use break and continue in for loops when processing a dataset
- Handle missing numeric values when computing a maximum/minimum
- Use the index of a maximum or minimum to access other information about that data item
## `for` loops, the `range()` function, and lists
If you know in advance how many times you want a loop to run, you may want to use a `for` loop. These loops are commonly used with the `range()` function or with a list when you want to do the same thing to each item in the list.
The `range()` function can be called with one argument specifying how high to count. It returns a range of values from 0 up to (**but not including**) the value that was passed in. This is helpful when working with a `for` loop. Try executing the code in the cell below:
%% Cell type:code id: tags:
``` python
for num in range(10):
print(num)
```
%% Cell type:markdown id: tags:
Notice that the `for` loop creates a variable (`num` in the example above). This variable holds a different value from the range each time the loop is executed.
The `range()` function can be called with two arguments as well. The first specifies the starting value and the second specifies the ending value (**but not including the ending value**). Try executing the code in the cell below:
%% Cell type:code id: tags:
``` python
for x in range(3, 7):
print(x,"*",x,"=",x*x)
```
%% Cell type:markdown id: tags:
`for` loops are also commonly used with lists. We will talk more about lists later, but a list can hold more than a single value. To create a list, use square brackets with the values inside separated by commas.
```python
fruits = ['Apple', 'Pear', 'Orange']
```
The `for` loop will iterate over the values in the list.
```python
fruits = ['Apple', 'Pear', 'Orange']
for fruit in fruits:
print(fruit)
```
You can also iterate over the characters in a string.
```python
name = "Louis"
for ch in name:
print(ch)
```
Try modifying and running the code in the cell below:
%% Cell type:code id: tags:
``` python
greetings = ["Hola", "Hello", "Dag", "Kon'nichiwa"]
for greeting in greetings:
print(greeting,"to you")
name = "Louis"
for c in name:
print(c)
```
%% Cell type:markdown id: tags:
For the remainder of the notebook we will be using a module (`project`) which loads a spreadsheet of information (`cs220_survey_data.csv`). Make sure you have both the project module and the csv file in the directory with this notebook, then run the two cells below to import the project and print its help documentation.
%% Cell type:code id: tags:
``` python
import project
```
%% Cell type:code id: tags:
``` python
help(project)
```
%% Cell type:code id: tags:
``` python
# Get the total # of responses
project.count()
```
%% Cell type:code id: tags:
``` python
# Get the first student's primary major.
# With indices, we always start from 0!
project.get_primary_major(0)
```
%% Cell type:code id: tags:
``` python
# Example 1: Print and Break
for i in range(project.count()):
print (i, project.get_primary_major(i))
if i == 10:
break
```
%% Cell type:code id: tags:
``` python
# TODO: Write the same code as above using a while loop!
```
%% Cell type:code id: tags:
``` python
# Example 2: How many students are not in Computer Science?
non_cs = 0
for i in range(project.count()):
major = project.get_primary_major(i)
if major == "Computer Science":
continue
non_cs += 1
print(non_cs, "out of", project.count(), "are non-cs!")
```
%% Cell type:code id: tags:
``` python
# TODO: How many students are in Data Science or Statistics?
# BONUS: Can you express this as a percentage?
# BONUS+: ...rounded to 2 decimal places?
```
%% Cell type:code id: tags:
``` python
# max = 0 # don't use built-in function names as variables
max_age = 0
for i in range(project.count()):
student_age = project.get_age(i)
if student_age > max_age:
max_age = student_age
print("The oldest student is", max_age)
# HINT: Did everyone fill out an age?
```
%% Cell type:code id: tags:
``` python
# TODO: What is the age of the youngest student?
```
%% Cell type:code id: tags:
``` python
# Example 5: How many early birds are there below the age of 21?
early_birds = 0
for i in range(project.count()):
sleep_habit = project.get_sleep_habit(i)
age = project.get_age(i)
if age != "":
age = int(age)
if ???: # TODO Complete this condition!
early_birds += 1
print("There are", early_birds, "early birds below the age of 21.")
```
%% Cell type:code id: tags:
``` python
# TODO: What percentage of 20-year-olds are early birds?
# BOUNUS: How can we generalize our code to 'What percentage of x-year-olds are early birds?'
```
%% Cell type:code id: tags:
``` python
# Other tasks for you to try...
# - What is the average age of the class?
# - What is the class's favorite pizza topping?
# - What is the most popular major?
# - For all students that have another major, print out what it is.
# - What zip code do the majority of pineapple-eating night owls live in?
```
This diff is collapsed.
__student__ = []
def __init__():
import csv
"""This function will read in the csv_file and store it in a list of dictionaries"""
__student__.clear()
with open('cs220_survey_data.csv', mode='r', encoding='utf-8') as csv_file:
csv_reader = csv.DictReader(csv_file)
for row in csv_reader:
__student__.append(row)
def count():
"""This function will return the number of records in the dataset"""
return len(__student__)
def get_lecture(idx):
"""get_lecture(idx) returns the lecture of the student in row idx"""
return __student__[int(idx)]['Lecture']
def get_section(idx):
"""get_lecture(idx) returns the section of the student in row idx"""
return __student__[int(idx)]['section']
def get_age(idx):
"""get_age(idx) returns the age of the student in row idx"""
return __student__[int(idx)]['Age']
def get_primary_major(idx):
"""get_primary_major(idx) returns the primary major of the student in row idx"""
return __student__[int(idx)]['Primary major']
def get_other_majors(idx):
"""get_other_majors(idx) returns the secondary major of the student in row idx"""
return __student__[int(idx)]['Other majors']
def get_zip_code(idx):
"""get_zip_code(idx) returns the residential zip code of the student in row idx"""
return __student__[int(idx)]['Zip Code']
def get_pizza_topping(idx):
"""get_pizza_topping(idx) returns the preferred pizza toppings of the student in row idx"""
return __student__[int(idx)]['Pizza topping']
def get_cats_or_dogs(idx):
"""get_cats_or_dogs(idx) returns whether student in row idx likes cats or dogs"""
return __student__[int(idx)]['Cats or dogs']
def get_runner(idx):
"""get_runner(idx) returns whether student in row idx is a runner"""
return __student__[int(idx)]['Runner']
def get_sleep_habit(idx):
"""get_sleep_habit(idx) returns the sleep habit of the student in row idx"""
return __student__[int(idx)]['Sleep habit']
def get_procrastinator(idx):
"""get_procrastinator(idx) returns whether student in row idx is a procrastinator"""
return __student__[int(idx)]['Procrastinator']
def get_song(idx):
"""get_procrastinator(idx) returns the student in row idx favorite song"""
return __student__[int(idx)]['Song']
__init__()
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