Skip to content
Snippets Groups Projects
Commit 3b2fe508 authored by Anna Meyer's avatar Anna Meyer
Browse files

after lec 7

parent 360d7777
No related branches found
No related tags found
No related merge requests found
%% Cell type:markdown id:6a76ef95 tags: %% Cell type:markdown id:6a76ef95 tags:
# Iteration Practice # Iteration Practice
%% Cell type:markdown id:103da70b tags: %% Cell type:markdown id:103da70b tags:
## Learning Objectives ## Learning Objectives
- Iterate through a dataset using for idx in range(project.count()) - Iterate through a dataset using for idx in range(project.count())
- Compute the frequency of data that meets a certain criteria - Compute the frequency of data that meets a certain criteria
- Find the maximum or minimum value of a numeric column in a dataset - Find the maximum or minimum value of a numeric column in a dataset
- Handle missing numeric values when computing a maximum / minimum - 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 - Use the index of a maximum or minimum to access other information about that data item
- Use break and continue in for loops when processing a dataset - Use break and continue in for loops when processing a dataset
- Trace the output of a nested loop algorithm that prints out a game grid - Trace the output of a nested loop algorithm that prints out a game grid
%% Cell type:code id:28961628 tags: %% Cell type:code id:28961628 tags:
``` python ``` python
import project import project
``` ```
%% Cell type:code id:c9341253 tags: %% Cell type:code id:c9341253 tags:
``` python ``` python
# TODO: inspect the functions inside project module # TODO: inspect the functions inside project module
dir(project) dir(project)
``` ```
%% Output %% Output
['__builtins__', ['__builtins__',
'__cached__', '__cached__',
'__doc__', '__doc__',
'__file__', '__file__',
'__init__', '__init__',
'__loader__', '__loader__',
'__name__', '__name__',
'__package__', '__package__',
'__spec__', '__spec__',
'__student__', '__student__',
'count', 'count',
'get_age', 'get_age',
'get_latitude', 'get_latitude',
'get_lecture', 'get_lecture',
'get_longitude', 'get_longitude',
'get_major', 'get_major',
'get_pet_owner', 'get_pet_owner',
'get_piazza_topping', 'get_piazza_topping',
'get_procrastinator', 'get_procrastinator',
'get_runner', 'get_runner',
'get_sleep_habit', 'get_sleep_habit',
'get_zip_code'] 'get_zip_code']
%% Cell type:code id:d1dca7ae tags: %% Cell type:code id:d1dca7ae tags:
``` python ``` python
# TODO: inspect the project module's documentation # TODO: inspect the project module's documentation
help(project) help(project)
``` ```
%% Output %% Output
Help on module project: Help on module project:
NAME NAME
project project
FUNCTIONS FUNCTIONS
__init__() __init__()
count() count()
This function will return the number of records in the dataset This function will return the number of records in the dataset
get_age(idx) get_age(idx)
get_age(idx) returns the age of the student in row idx get_age(idx) returns the age of the student in row idx
get_latitude(idx) get_latitude(idx)
get_latitude(idx) returns the latitude of the student's favourite place in row idx get_latitude(idx) returns the latitude of the student's favourite place in row idx
get_lecture(idx) get_lecture(idx)
get_lecture(idx) returns the lecture of the student in row idx get_lecture(idx) returns the lecture of the student in row idx
get_longitude(idx) get_longitude(idx)
get_longitude(idx) returns the longitude of the student's favourite place in row idx get_longitude(idx) returns the longitude of the student's favourite place in row idx
get_major(idx) get_major(idx)
get_major(idx) returns the major of the student in row idx get_major(idx) returns the major of the student in row idx
get_pet_owner(idx) get_pet_owner(idx)
get_pet_owner(idx) returns the pet preference of student in row idx get_pet_owner(idx) returns the pet preference of student in row idx
get_piazza_topping(idx) get_piazza_topping(idx)
get_piazza_topping(idx) returns the preferred pizza toppings of the student in row idx get_piazza_topping(idx) returns the preferred pizza toppings of the student in row idx
get_procrastinator(idx) get_procrastinator(idx)
get_procrastinator(idx) returns whether student in row idx is a procrastinator get_procrastinator(idx) returns whether student in row idx is a procrastinator
get_runner(idx) get_runner(idx)
get_runner(idx) returns whether student in row idx is a runner get_runner(idx) returns whether student in row idx is a runner
get_sleep_habit(idx) get_sleep_habit(idx)
get_sleep_habit(idx) returns the sleep habit of the student in row idx get_sleep_habit(idx) returns the sleep habit of the student in row idx
get_zip_code(idx) get_zip_code(idx)
get_zip_code(idx) returns the residential zip code of the student in row idx get_zip_code(idx) returns the residential zip code of the student in row idx
DATA DATA
__student__ = [{'Age': '22', 'Latitude': '43.073051', 'Lecture': 'LEC0... __student__ = [{'Age': '22', 'Latitude': '43.073051', 'Lecture': 'LEC0...
FILE FILE
/Users/annameyer/DocumentsLocal/teaching/cs220-lecture-material/sum23/lecture_materials/06_Iteration1/project.py /Users/annameyer/DocumentsLocal/teaching/cs220-lecture-material/sum23/lecture_materials/06_Iteration1/project.py
%% Cell type:markdown id:7fb78f6b tags: %% Cell type:markdown id:7fb78f6b tags:
### How many students does the dataset have? ### How many students does the dataset have?
%% Cell type:code id:d67a080f tags: %% Cell type:code id:d67a080f tags:
``` python ``` python
project.count() project.count()
``` ```
%% Output %% Output
992 992
%% Cell type:markdown id:3c97d494 tags: %% Cell type:markdown id:3c97d494 tags:
### What is the age of the student at index 10? ### What is the age of the student at index 10?
%% Cell type:code id:bde8dc35 tags: %% Cell type:code id:bde8dc35 tags:
``` python ``` python
id_10_age = project.get_age(10) id_10_age = project.get_age(10)
id_10_age id_10_age
``` ```
%% Output %% Output
'21' '21'
%% Cell type:code id:b0f87a2c tags: %% Cell type:code id:b0f87a2c tags:
``` python ``` python
# TODO: inspect return value type of get_age function # TODO: inspect return value type of get_age function
print(type(id_10_age)) print(type(id_10_age))
``` ```
%% Output %% Output
<class 'str'> <class 'str'>
%% Cell type:markdown id:37898141 tags: %% Cell type:markdown id:37898141 tags:
### What is the lecture number of the student at index 20? ### What is the lecture number of the student at index 20?
%% Cell type:code id:ba993090 tags: %% Cell type:code id:ba993090 tags:
``` python ``` python
project.get_lecture(20) project.get_lecture(20)
``` ```
%% Output %% Output
'LEC001' 'LEC001'
%% Cell type:markdown id:60730da8 tags: %% Cell type:markdown id:60730da8 tags:
### What is the sleep habit of the student at the last index? ### What is the sleep habit of the student at the last index?
%% Cell type:code id:1d92e499 tags: %% Cell type:code id:1d92e499 tags:
``` python ``` python
project.get_sleep_habit(project.count() - 1) project.get_sleep_habit(project.count() - 1)
``` ```
%% Output %% Output
'night owl' 'night owl'
%% Cell type:markdown id:af3d9d8c tags: %% Cell type:markdown id:af3d9d8c tags:
### How many current lecture (example: LEC001) students are in the dataset? ### How many current lecture (example: LEC001) students are in the dataset?
- use `for` loop to iterate over the dataset: - use `for` loop to iterate over the dataset:
- `count` function gives you total number of students - `count` function gives you total number of students
- use `range` built-in function to generate sequence of integers from `0` to `count - 1` - use `range` built-in function to generate sequence of integers from `0` to `count - 1`
- use `get_lecture` to retrieve lecture column value - use `get_lecture` to retrieve lecture column value
- use `if` condition, to determine whether current student is part of `LEC001` - use `if` condition, to determine whether current student is part of `LEC001`
- `True` evaluation: increment count - `True` evaluation: increment count
- `False` evaluation: nothing to do - `False` evaluation: nothing to do
%% Cell type:code id:e024c488 tags: %% Cell type:code id:e024c488 tags:
``` python ``` python
count = 0 count = 0
for idx in range(project.count()): for idx in range(project.count()):
lecture_num = project.get_lecture(idx) lecture_num = project.get_lecture(idx)
if lecture_num == 'LEC001': if lecture_num == 'LEC001':
count += 1 count += 1
print(count) print(count)
``` ```
%% Output %% Output
195 195
%% Cell type:code id:c6a2ddf7 tags: %% Cell type:code id:c6a2ddf7 tags:
``` python ``` python
``` ```
%% Cell type:markdown id:b9ff6434 tags: %% Cell type:markdown id:b9ff6434 tags:
### What is the age of the oldest student in current lecture (example: LEC001)? ### What is the age of the oldest student in current lecture (example: LEC001)?
- use `for` loop to iterate over the dataset just like last problem - use `for` loop to iterate over the dataset just like last problem
- use `get_age` to retrieve lecture column value - use `get_age` to retrieve lecture column value
- if: age is '' (empty), move on to next student using `continue` - if: age is '' (empty), move on to next student using `continue`
- make sure to typecast return value to an integer - make sure to typecast return value to an integer
- use `get_lecture` to retrieve lecture column value - use `get_lecture` to retrieve lecture column value
- use `if` condition, to determine whether current student is part of `LEC001` - use `if` condition, to determine whether current student is part of `LEC001`
- use `if` condition to determine whether current student's age is greater than previously known max age - use `if` condition to determine whether current student's age is greater than previously known max age
- `True` evaluation: replace previously known max age with current age - `True` evaluation: replace previously known max age with current age
- `False` evaluation: nothing to do - `False` evaluation: nothing to do
%% Cell type:code id:38bd778a tags: %% Cell type:code id:38bd778a tags:
``` python ``` python
max_age = 0 # max_age = 0 # Anna did it like this in lecture, but this isn't good style
max_age = None
for idx in range(project.count()): for idx in range(project.count()):
age = project.get_age(idx) age = project.get_age(idx)
if age == '': if age == '':
continue continue
age = int(age) age = int(age)
lecture_num = project.get_lecture(idx) lecture_num = project.get_lecture(idx)
if lecture_num == 'LEC001': if lecture_num == 'LEC001':
if age > max_age: if max_age == None or age > max_age:
max_age = age max_age = age
print(max_age) print(max_age)
``` ```
%% Output %% Output
37 37
%% Cell type:markdown id:b40a32fb tags: %% Cell type:markdown id:b40a32fb tags:
### What is the age of the youngest student in current lecture (example: LEC001)? ### What is the age of the youngest student in current lecture (example: LEC001)?
- use similar algorithm as above question - use similar algorithm as above question
%% Cell type:code id:ea77e0cd tags: %% Cell type:code id:ea77e0cd tags:
``` python ``` python
``` ```
%% Cell type:markdown id:296c2a49 tags: %% Cell type:markdown id:296c2a49 tags:
### What is the average age of students enrolled in CS220 / CS319? ### What is the average age of students enrolled in CS220 / CS319?
- you will get an interesting answer :) - you will get an interesting answer :)
- how can we ensure that data doesn't skew statistics? - how can we ensure that data doesn't skew statistics?
%% Cell type:code id:8b7c8367 tags: %% Cell type:code id:8b7c8367 tags:
``` python ``` python
total = 0 total = 0
number_of_students = 0 number_of_students = 0
for idx in range(project.count()): for idx in range(project.count()):
age = project.get_age(idx) age = project.get_age(idx)
if age == '': if age == '':
continue continue
age = int(age) age = int(age)
#TODO: make sure age is real #TODO: make sure age is real
total += age total += age
number_of_students += 1 number_of_students += 1
print("Average age is:", total / number_of_students) print("Average age is:", total / number_of_students)
``` ```
%% Output %% Output
Average age is: 64.8225806451613 Average age is: 64.8225806451613
%% Cell type:markdown id:48f1c791 tags: %% Cell type:markdown id:48f1c791 tags:
### What major is the youngest student in current lecture (example: LEC001) planning to declare? ### What major is the youngest student in current lecture (example: LEC001) planning to declare?
- now, we need to find some other detail about the youngest student - now, we need to find some other detail about the youngest student
- often, you'll have to keep track of ID of the max or min, so that you can retrive other details about that data entry - often, you'll have to keep track of ID of the max or min, so that you can retrive other details about that data entry
%% Cell type:code id:a524873b tags: %% Cell type:code id:a524873b tags:
``` python ``` python
# NOTE: this works, but is bad style. Instead, we should initalize min_age and min_age_idx to `None` # NOTE: this works, but is bad style. Instead, we should initalize min_age and min_age_idx to `None`
# (Anna will discuss this in class on Wednesday) # (Anna will discuss this in class on Wednesday)
min_age = 99 # min_age = 99
min_age_idx = -1 # min_age_idx = -1
# do this instead:
min_age = None
min_age_idx = None
for idx in range(project.count()): for idx in range(project.count()):
age = project.get_age(idx) age = project.get_age(idx)
if age == '': if age == '':
continue continue
age = int(age) age = int(age)
lecture_number = project.get_lecture(idx) lecture_number = project.get_lecture(idx)
if lecture_number != "LEC001": if lecture_number != "LEC001":
continue continue
if age < min_age: if min_age == None or age < min_age:
min_age = age min_age = age
min_age_idx = idx min_age_idx = idx
print(project.get_major(idx)) print(project.get_major(idx))
``` ```
%% Output %% Output
Economics Economics
%% Cell type:code id:e4fe17ae tags: %% Cell type:code id:e4fe17ae tags:
``` python ``` python
``` ```
%% Cell type:markdown id:5294702a tags: %% Cell type:markdown id:5294702a tags:
### Considering current lecture students (example: LEC001), what is the age of the first student residing at zip code 53715? ### Considering current lecture students (example: LEC001), what is the age of the first student residing at zip code 53715?
%% Cell type:code id:fada2a40 tags: %% Cell type:code id:fada2a40 tags:
``` python ``` python
``` ```
%% Cell type:markdown id:68793d99 tags: %% Cell type:markdown id:68793d99 tags:
## Self-practice ## Self-practice
%% Cell type:markdown id:2eeed867 tags: %% Cell type:markdown id:2eeed867 tags:
### How many current lecture (example: LEC001) students are runners? ### How many current lecture (example: LEC001) students are runners?
%% Cell type:markdown id:1ea57e12 tags: %% Cell type:markdown id:1ea57e12 tags:
### How many current lecture (example: LEC001) students are procrastinators? ### How many current lecture (example: LEC001) students are procrastinators?
%% Cell type:markdown id:cf0ac7c8 tags: %% Cell type:markdown id:cf0ac7c8 tags:
### How many current lecture (example: LEC001) students own or have owned a pet? ### How many current lecture (example: LEC001) students own or have owned a pet?
%% Cell type:markdown id:ffd5e10f tags: %% Cell type:markdown id:ffd5e10f tags:
### What sleep habit does the youngest student in current lecture (example: LEC001) have? ### What sleep habit does the youngest student in current lecture (example: LEC001) have?
- try to solve this from scratch, instead of copy-pasting code to find mimimum age - try to solve this from scratch, instead of copy-pasting code to find mimimum age
%% Cell type:markdown id:f255b95a tags: %% Cell type:markdown id:f255b95a tags:
### What sleep habit does the oldest student in current lecture (example: LEC001) have? ### What sleep habit does the oldest student in current lecture (example: LEC001) have?
- try to solve this from scratch, instead of copy-pasting code to find mimimum age - try to solve this from scratch, instead of copy-pasting code to find mimimum age
%% Cell type:markdown id:db60812c tags: %% Cell type:markdown id:db60812c tags:
### Considering current lecture students (example: LEC001), is the first student with age 18 a runner? ### Considering current lecture students (example: LEC001), is the first student with age 18 a runner?
%% Cell type:markdown id:70a8ac57 tags: %% Cell type:markdown id:70a8ac57 tags:
### What is the minimum latitude (& corresponding longitude) of a student's place of interest? ### What is the minimum latitude (& corresponding longitude) of a student's place of interest?
- What place is this -> try to enter the lat, long on Google maps? - What place is this -> try to enter the lat, long on Google maps?
%% Cell type:markdown id:581ea197 tags: %% Cell type:markdown id:581ea197 tags:
### What is the maximum latitude (& corresponding longitude) of a student's place of interest? ### What is the maximum latitude (& corresponding longitude) of a student's place of interest?
- What place is this -> try to enter the lat, long on Google maps? - What place is this -> try to enter the lat, long on Google maps?
%% Cell type:code id:333cd894 tags: %% Cell type:code id:333cd894 tags:
``` python ``` python
maximum_latitude = -1000 # Note: initialize maximum_latitude and max_idx to None (not real numbers, like Anna did in class)
max_idx = -1 maximum_latitude = None
max_idx = None
for idx in range(project.count()): for idx in range(project.count()):
latitude = float(project.get_latitude(idx)) latitude = float(project.get_latitude(idx))
if abs(latitude) > 90: if abs(latitude) > 90:
continue continue
if latitude > maximum_latitude: # first check if maximum_latitude is None, then check if current latitude is larger than current max
if maximum_latitude == None or latitude > maximum_latitude:
maximum_latitude = latitude maximum_latitude = latitude
max_idx = idx max_idx = idx
print("maximum latitude is ",maximum_latitude) print("maximum latitude is ",maximum_latitude)
print("corresponding longitude is ",project.get_longitude(max_idx)) print("corresponding longitude is ",project.get_longitude(max_idx))
``` ```
%% Output %% Output
maximum latitude is 78.225 maximum latitude is 78.225
corresponding longitude is 15.626 corresponding longitude is 15.626
%% Cell type:markdown id:5f943c98 tags: %% Cell type:markdown id:5f943c98 tags:
### What is the minimum longitude (& corresponding latitude) of a student's place of interest? ### What is the minimum longitude (& corresponding latitude) of a student's place of interest?
- What place is this -> try to enter the lat, long on Google maps? - What place is this -> try to enter the lat, long on Google maps?
%% Cell type:code id:d3e7fad2 tags: %% Cell type:code id:d3e7fad2 tags:
``` python ``` python
# NOTE: this isn't the best way to initialize variables minimum_longitude = None
minimum_longitude = 1000 min_idx = None
min_idx = -1
for idx in range(project.count()): for idx in range(project.count()):
longitude = float(project.get_longitude(idx)) longitude = float(project.get_longitude(idx))
if abs(longitude) > 90: if abs(longitude) > 90:
continue continue
if longitude < minimum_longitude: if minimum_longitude == None or longitude < minimum_longitude:
minimum_longitude = longitude minimum_longitude = longitude
min_idx = idx min_idx = idx
print("minimum longitude is ",minimum_longitude) print("minimum longitude is ",minimum_longitude)
print("corresponding latitude is ",project.get_latitude(min_idx)) print("corresponding latitude is ",project.get_latitude(min_idx))
``` ```
%% Output %% Output
minimum longitude is -90.0 minimum longitude is -90.0
corresponding latitude is 40 corresponding latitude is 40
%% Cell type:markdown id:dceca301 tags: %% Cell type:markdown id:dceca301 tags:
The previous cell works, but it requires us to initalize think through how to cleverly initialize variables. The previous cell works, but it requires us to initalize think through how to cleverly initialize variables.
Instead, we can initialize variables to `None` outside of the loop. Notice that in line 11 below, we add a check `minimum_longitude is None` to the `if` statement. This guarantees that we will not get a type error when we check `longitude < minimum_longitude`. Instead, we can initialize variables to `None` outside of the loop. Notice that in line 11 below, we add a check `minimum_longitude is None` to the `if` statement. This guarantees that we will not get a type error when we check `longitude < minimum_longitude`.
%% Cell type:code id:4b2415ec tags: %% Cell type:code id:4b2415ec tags:
``` python ``` python
# better code -- we initialize variables to None # better code -- we initialize variables to None
minimum_longitude = None minimum_longitude = None
min_idx = None min_idx = None
for idx in range(project.count()): for idx in range(project.count()):
longitude = float(project.get_longitude(idx)) longitude = float(project.get_longitude(idx))
if abs(longitude) > 90: if abs(longitude) > 90:
continue continue
# introduce a check for minimum_longitude is None or (original condition) # introduce a check for minimum_longitude is None or (original condition)
if minimum_longitude is None or longitude < minimum_longitude: if minimum_longitude == None or longitude < minimum_longitude:
minimum_longitude = longitude minimum_longitude = longitude
min_idx = idx min_idx = idx
print("minimum longitude is ",minimum_longitude) print("minimum longitude is ",minimum_longitude)
print("corresponding latitude is ",project.get_latitude(min_idx)) print("corresponding latitude is ",project.get_latitude(min_idx))
``` ```
%% Cell type:markdown id:9b104a50 tags: %% Cell type:markdown id:9b104a50 tags:
### What is the maximum longitude (& corresponding latitude) of a student's place of interest? ### What is the maximum longitude (& corresponding latitude) of a student's place of interest?
- What place is this -> try to enter the lat, long on Google maps? - What place is this -> try to enter the lat, long on Google maps?
%% Cell type:code id:fcee0994 tags: %% Cell type:code id:fcee0994 tags:
``` python ``` python
``` ```
......
%% Cell type:markdown id:482016d5 tags: %% Cell type:markdown id:482016d5 tags:
# Exam 1 review # Exam 1 review
%% Cell type:markdown id:96330469 tags: %% Cell type:markdown id:96330469 tags:
## Arguments ## Arguments
%% Cell type:code id:138a92cc tags: %% Cell type:code id:138a92cc tags:
``` python ``` python
def person(name, age, color='blue', animal='cat'): def person(name, age, color='blue', animal='cat'):
print(name, " is ", age, " years old ", end="") print(name, " is ", age, " years old ", end="")
print("their favorite color is ",color, end="") print("their favorite color is ",color, end="")
print(" and their favorite animal is ",animal) print(" and their favorite animal is ",animal)
``` ```
%% Cell type:code id:a5f2edbc tags: %% Cell type:code id:a5f2edbc tags:
``` python ``` python
# TODO: what are all the ways we can (or cannot) call person()? # TODO: what are all the ways we can (or cannot) call person()?
person("Anna", 10, "purple", "fish")
person("Anna", 10, "purple")
# person("Anna") # doesn't work, need to specify age
person("Anna", age=20)
# person(age=20, "Anna") # doesn't work, need to specify positional arguments first
person(age=20, name="Anna")
person(animal="zebra", age=20, name="Anna")
# person(20, name="Anna") # doesn't work, positional parameters fill first from left to right
person(20, 20)
``` ```
%% Cell type:markdown id:6f623b4b tags: %% Cell type:markdown id:6f623b4b tags:
## Function Scope ## Function Scope
%% Cell type:markdown id:e54320ef tags: %% Cell type:markdown id:e54320ef tags:
### Example 1 -- basic function scope ### Example 1 -- basic function scope
%% Cell type:code id:7e4d570a tags: %% Cell type:code id:7e4d570a tags:
``` python ``` python
pi = 3.14 pi = 3.14
alpha = 4 alpha = 4
def my_func(alpha, beta): def my_func(alpha, beta):
# TODO: what variables are accessible at line 5? what values do they have? # TODO: what variables are accessible at line 5? what values do they have?
# we can access these local variables:
# -- alpha (has value of parameter passed into function)
# -- beta (has value of parameter passed into function)
# -- pi (global variable, value = 3.14)
delta = alpha + beta delta = alpha + beta
gamma = delta ** 2 gamma = delta ** 2
return gamma return gamma
answer = my_func(alpha, pi) answer = my_func(alpha, pi)
answer2 = my_func(answer, alpha) answer2 = my_func(answer, alpha)
# TODO what variables are accessible here? What values do they have? # TODO what variables are accessible here? What values do they have?
# CANNOT access delta, gamma, beta
# alpha = 4 (note that using the variable name alpha in my_func does not change the global variable)
``` ```
%% Cell type:markdown id:33a302bf tags: %% Cell type:markdown id:33a302bf tags:
### Example 2 -- global vs. local ### Example 2 -- global vs. local
%% Cell type:code id:7a5ed848 tags: %% Cell type:code id:7a5ed848 tags:
``` python ``` python
two = 3.14 two = 2
alpha = 4 alpha = 4
def my_func1(alpha, beta): def my_func1(alpha, beta):
# TODO: what variables are accessible at line 5? what values do they have? # TODO: what variables are accessible at line 5? what values do they have?
delta = alpha + beta delta = alpha + beta
gamma = delta * two gamma = delta * two
return gamma return gamma
answer = my_func(alpha, two) answer = my_func1(alpha, two)
print(answer)
# TODO what variables are accessible here? What values do they have? # TODO what variables are accessible here? What values do they have?
``` ```
%% Cell type:code id:04428811 tags: %% Cell type:code id:04428811 tags:
``` python ``` python
two = 2 two = 2
alpha = 14 alpha = 14
def my_func2(alpha, beta): def my_func2(alpha, beta):
# TODO: what variables are accessible at line 5? what values do they have? # TODO: what variables are accessible at line 5? what values do they have?
delta = alpha + beta delta = alpha + beta
two = 7 two = 7
gamma = delta * two gamma = delta * two
return gamma return gamma
answer = my_func(alpha, two) answer = my_func2(alpha, two)
print(answer)
# TODO what variables are accessible here? What values do they have? # TODO what variables are accessible here? What values do they have?
``` ```
%% Cell type:code id:51696c45 tags: %% Cell type:code id:51696c45 tags:
``` python ``` python
two = 2 two = 2
alpha = 14 alpha = 14
def my_func3(alpha, beta): def my_func3(alpha, beta):
# TODO: what variables are accessible at line 5? what values do they have? # TODO: what variables are accessible at line 5? what values do they have?
delta = alpha + beta delta = alpha + beta
gamma = delta * two gamma = delta * two
two = 7 two = 7
return gamma return gamma
answer = my_func(alpha, two) answer = my_func3(alpha, two)
# TODO what variables are accessible here? What values do they have? # TODO what variables are accessible here? What values do they have?
``` ```
%% Cell type:code id:6cdb7a02 tags: %% Cell type:code id:6cdb7a02 tags:
``` python ``` python
two = 2 two = 2
alpha = 14 alpha = 14
def my_func3(alpha, beta): def my_func3(alpha, beta):
# TODO: what variables are accessible at line 5? what values do they have? # TODO: what variables are accessible at line 5? what values do they have?
global delta # adding this in to show how we create a global variable in a function
delta = alpha + beta delta = alpha + beta
global two global two
gamma = delta * two gamma = delta * two
two = 7 two = 7
return gamma return gamma
answer = my_func(alpha, two) answer = my_func3(alpha, two)
print(answer)
# TODO what variables are accessible here? What values do they have? # TODO what variables are accessible here? What values do they have?
``` ```
%% Cell type:markdown id:2ebbfa8b tags: %% Cell type:markdown id:2ebbfa8b tags:
## Refactoring ## Refactoring
%% Cell type:markdown id:c61c0d46 tags: %% Cell type:markdown id:c61c0d46 tags:
### Example 1 ### Example 1
%% Cell type:code id:7e25ba85 tags: %% Cell type:code id:7e25ba85 tags:
``` python ``` python
def some_func(): def some_func():
if some_cond1: if some_cond1:
if some_cond2: if some_cond2:
if some_cond3: if some_cond3:
return True return True
return False return False
``` ```
%% Cell type:code id:d6dc250a tags: %% Cell type:code id:d6dc250a tags:
``` python ``` python
# TODO how can we rewrite some_func() to only use 1 line of code? # TODO how can we rewrite some_func() to only use 1 line of code?
def some_func_short(): def some_func_short():
pass pass
``` ```
%% Cell type:markdown id:b9da2d00 tags: %% Cell type:markdown id:b9da2d00 tags:
### Example 2 ### Example 2
%% Cell type:code id:678f8ec2 tags: %% Cell type:code id:678f8ec2 tags:
``` python ``` python
def some_func_1(x, y, z): def some_func_1(x, y, z):
if x >= 7: if x >= 7:
return True return True
if y < 18: elif y < 18:
return True return True
if z == 32: elif z == 32:
return True return True
else: else:
return False return False
``` ```
%% Cell type:code id:d1bf3938 tags: %% Cell type:code id:d1bf3938 tags:
``` python ``` python
# TODO which of these refactoring options is correct? # TODO which of these refactoring options is correct?
def some_func_1a(x, y, z): def some_func_1a(x, y, z):
return x >= 7 or y < 18 or z == 32 return x >= 7 or y < 18 or z == 32
def some_func_1b(x, y, z): def some_func_1b(x, y, z):
return x >= 7 and y < 18 and z == 32 return x >= 7 and y < 18 and z == 32
```
%% Cell type:code id:063829c0 tags:
``` python
# TODO
# Discuss: given two possible versions of a function (where one is correct),
# what is the general strategy for figuring out which one is correct?
``` ```
%% Cell type:markdown id:d1ba721c tags: %% Cell type:markdown id:bbfbdfcc tags:
## Iteration ## Iteration
%% Cell type:markdown id:851c3e95 tags: %% Cell type:markdown id:55b93aa1 tags:
### Example 1 (Reimann sums) ### Example 1 (Reimann sums)
%% Cell type:code id:85e203c9 tags: %% Cell type:code id:eda1fd93 tags:
``` python
# copied from lecture 6 notes
def f(x):
return 5 - (x - 2) ** 2
print(f(1))
```
%% Cell type:code id:6a58812c tags:
``` python ``` python
# Let's try the values from 1 to 5 # Let's try the values from 1 to 5
start_x = 1 start_x = 1
end_x = 5 end_x = 5
total_area = 0 total_area = 0
current_x = start_x current_x = start_x
# Try out increasing values of width, make sure to comment the other width values # Try out increasing values of width, make sure to comment the other width values
# delta_x = 1 # delta_x = 1
delta_x = 0.1 delta_x = 0.1
# delta_x = 0.01 # delta_x = 0.01
# delta_x = 0.001 # delta_x = 0.001
while current_x <= end_x: while current_x <= ???:
y = ??? # TODO: use f(x) defined previously y = ??? # TODO: use f(x) defined previously
rect_area = ??? rect_area = ???
total_area += ??? total_area += ???
current_x += delta_x current_x += delta_x
print("Area found using approximation is:", total_area) print("Area found using approximation is:", total_area)
``` ```
%% Cell type:code id:a9d49036 tags:
``` python
```
......
%% Cell type:markdown id:482016d5 tags:
# Exam 1 review
%% Cell type:markdown id:96330469 tags:
## Arguments
%% Cell type:code id:138a92cc tags:
``` python
def person(name, age, color='blue', animal='cat'):
print(name, " is ", age, " years old ", end="")
print("their favorite color is ",color, end="")
print(" and their favorite animal is ",animal)
```
%% Cell type:code id:a5f2edbc tags:
``` python
# TODO: what are all the ways we can (or cannot) call person()?
person("Anna", 10, "purple", "fish")
person("Anna", 10, "purple")
# person("Anna") # doesn't work, need to specify age
person("Anna", age=20)
# person(age=20, "Anna") # doesn't work, need to specify positional arguments first
person(age=20, name="Anna")
person(animal="zebra", age=20, name="Anna")
# person(20, name="Anna") # doesn't work, positional parameters fill first from left to right
person(20, 20)
```
%% Output
Anna is 10 years old their favorite color is purple and their favorite animal is fish
Anna is 10 years old their favorite color is purple and their favorite animal is cat
Anna is 20 years old their favorite color is blue and their favorite animal is cat
Anna is 20 years old their favorite color is blue and their favorite animal is cat
Anna is 20 years old their favorite color is blue and their favorite animal is zebra
20 is 20 years old their favorite color is blue and their favorite animal is cat
%% Cell type:markdown id:6f623b4b tags:
## Function Scope
%% Cell type:markdown id:e54320ef tags:
### Example 1 -- basic function scope
%% Cell type:code id:7e4d570a tags:
``` python
pi = 3.14
alpha = 4
def my_func(alpha, beta):
# TODO: what variables are accessible at line 5? what values do they have?
# we can access these local variables:
# -- alpha (has value of parameter passed into function)
# -- beta (has value of parameter passed into function)
# -- pi (global variable, value = 3.14)
delta = alpha + beta
gamma = delta ** 2
return gamma
answer = my_func(alpha, pi)
answer2 = my_func(answer, alpha)
# TODO what variables are accessible here? What values do they have?
# CANNOT access delta, gamma, beta
# alpha = 4 (note that using the variable name alpha in my_func does not change the global variable)
```
%% Cell type:markdown id:33a302bf tags:
### Example 2 -- global vs. local
%% Cell type:code id:7a5ed848 tags:
``` python
two = 2
alpha = 4
def my_func1(alpha, beta):
# TODO: what variables are accessible at line 5? what values do they have?
# can access two (global), alpha (local), and beta (local)
delta = alpha + beta
gamma = delta * two
return gamma
answer = my_func1(alpha, two)
print(answer)
# TODO what variables are accessible here? What values do they have?
# can access two (value=2), alpha (value=4), and answer
```
%% Output
12
%% Cell type:code id:04428811 tags:
``` python
two = 2
alpha = 14
def my_func2(alpha, beta):
# TODO: what variables are accessible at line 5? what values do they have?
# can access alpha (local), beta, two (global)
delta = alpha + beta
two = 7
gamma = delta * two
return gamma
answer = my_func2(alpha, two)
print(answer)
# TODO what variables are accessible here? What values do they have?
# can access two (value=2, global variable two is not affected by line 8), alpha (14), and answer (112)
```
%% Output
112
%% Cell type:code id:51696c45 tags:
``` python
two = 2
alpha = 14
def my_func3(alpha, beta):
# TODO: what variables are accessible at line 5? what values do they have?
# can access alpha and beta
# CANNOT access global variable two because we define a local version of two later in this function
delta = alpha + beta
gamma = delta * two
two = 7
return gamma
# oops, there was a typo in the template: next line should call my_func3 not my_func
answer = my_func3(alpha, two)
# TODO what variables are accessible here? What values do they have?
# N/A: this code crashes because in line 10 we access the local variable "two" before it is defined
```
%% Output
---------------------------------------------------------------------------
UnboundLocalError Traceback (most recent call last)
Cell In[5], line 13
10 return gamma
12 # oops, there was a typo in the template: next line should call my_func3 not my_func
---> 13 answer = my_func3(alpha, two)
15 # TODO what variables are accessible here? What values do they have?
Cell In[5], line 8, in my_func3(alpha, beta)
4 def my_func3(alpha, beta):
5 # TODO: what variables are accessible at line 5? what values do they have?
6 delta = alpha + beta
----> 8 gamma = delta * two
9 two = 7
10 return gamma
UnboundLocalError: local variable 'two' referenced before assignment
%% Cell type:code id:6cdb7a02 tags:
``` python
two = 2
alpha = 14
def my_func3(alpha, beta):
# TODO: what variables are accessible at line 5? what values do they have?
# can access two (global), alpha (local), beta (local)
global delta # adding this in to show how we create a global variable in a function
delta = alpha + beta
global two
gamma = delta * two
two = 7
return gamma
# oops, there was a typo in the template: next line should call my_func3 not my_func
answer = my_func3(alpha, two)
print(answer)
# TODO what variables are accessible here? What values do they have?
# can access two (value=7), alpha (value=14), delta (value = 16), answer (value=32)
```
%% Output
32
%% Cell type:markdown id:2ebbfa8b tags:
## Refactoring
%% Cell type:markdown id:c61c0d46 tags:
### Example 1
%% Cell type:code id:7e25ba85 tags:
``` python
def some_func():
if some_cond1:
if some_cond2:
if some_cond3:
return True
return False
```
%% Cell type:code id:d6dc250a tags:
``` python
# TODO how can we rewrite some_func() to only use 1 line of code?
def some_func_short():
return some_cond1 and some_cond2 and some_cond3
some_cond1 = True
some_cond2 = True
some_cond3 = True
print(some_func())
print(some_func_short())
```
%% Output
True
True
%% Cell type:markdown id:b9da2d00 tags:
### Example 2
%% Cell type:code id:678f8ec2 tags:
``` python
def some_func_1(x, y, z):
# trial 1: x = 8, y = 19, z = 32
if x >= 7:
return True
elif y < 18:
return True
elif z == 32:
return True
else:
return False
```
%% Cell type:code id:d1bf3938 tags:
``` python
# TODO which of these refactoring options is correct?
def some_func_1a(x, y, z):
return x >= 7 or y < 18 or z == 32
def some_func_1b(x, y, z):
return x >= 7 and y < 18 and z == 32
print(some_func_1(8, 19, 32))
print(some_func_1a(8, 19, 32))
print(some_func_1b(8, 19, 32))
```
%% Output
True
True
False
%% Cell type:markdown id:718663c1 tags:
TODO
Discuss: given two possible versions of a function (where one is correct), what is the general strategy for figuring out which one is correct?
1. Check what kind of conditionals you have: nested or chained
- If nested, usually use "and"
- If chained, usually use "or"
- But be careful, because the addition of "not" or "False" will change things
2. Test cases to see what answers agree
- Assign parameter values and trace through each function using these same values. Check whether the output agrees.
- If a function takes only 2 True/False inputs, there are only 4 combinations of inputs total. It's usually possible to check the 4 possible outcomes by hand.
3. Use logic.
- Listing out by hand when the function will return True or False
- What parameters can you use to get the function to execute particular paths?
%% Cell type:markdown id:bbfbdfcc tags:
## Iteration
%% Cell type:markdown id:55b93aa1 tags:
### Example 1 (Reimann sums)
%% Cell type:code id:eda1fd93 tags:
``` python
# copied from lecture 6 notes
def f(x):
return 5 - (x - 2) ** 2
print(f(1))
```
%% Output
4
%% Cell type:code id:6a58812c tags:
``` python
# Let's try the values from 1 to 5
start_x = 1
end_x = 5
total_area = 0
current_x = start_x
# Try out increasing values of width, make sure to comment the other width values
# delta_x = 1
# delta_x = 0.1
# delta_x = 0.01
delta_x = 0.001
while current_x <= end_x:
y = f(current_x) # TODO: use f(x) defined previously
rect_area = delta_x * y
total_area += rect_area
current_x += delta_x
print("Area found using approximation is:", total_area)
```
%% Output
Area found using approximation is: 10.670666000001766
%% Cell type:code id:a9d49036 tags:
``` python
```
Source diff could not be displayed: it is too large. Options to address this: view the blob.
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