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

lec 6 materials

parent e3f1f715
No related branches found
No related tags found
No related merge requests found
This diff is collapsed.
%% Cell type:markdown id:6a76ef95 tags:
# Iteration Practice
%% Cell type:markdown id:103da70b tags:
## Learning Objectives
- 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
- 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 break and continue in for loops when processing a dataset
- Trace the output of a nested loop algorithm that prints out a game grid
%% Cell type:code id:28961628 tags:
``` python
import project
```
%% Cell type:code id:c9341253 tags:
``` python
# TODO: inspect the functions inside project module
```
%% Cell type:code id:d1dca7ae tags:
``` python
# TODO: inspect the project module's documentation
```
%% Cell type:markdown id:7fb78f6b tags:
### How many students does the dataset have?
%% Cell type:code id:d67a080f tags:
``` python
```
%% Cell type:markdown id:3c97d494 tags:
### What is the age of the student at index 10?
%% Cell type:code id:bde8dc35 tags:
``` python
id_10_age = project.???
id_10_age
```
%% Cell type:code id:b0f87a2c tags:
``` python
# TODO: inspect return value type of get_age function
print(type(id_10_age))
```
%% Cell type:markdown id:37898141 tags:
### What is the lecture number of the student at index 20?
%% Cell type:code id:ba993090 tags:
``` python
```
%% Cell type:markdown id:60730da8 tags:
### What is the sleep habit of the student at the last index?
%% Cell type:code id:1d92e499 tags:
``` python
project.???(???)
```
%% Cell type:markdown id:af3d9d8c tags:
### How many current lecture (example: LEC001) students are in the dataset?
- use `for` loop to iterate over the dataset:
- `count` function gives you total number of students
- use `range` built-in function to generate sequence of integers from `0` to `count - 1`
- use `get_lecture` to retrieve lecture column value
- use `if` condition, to determine whether current student is part of `LEC001`
- `True` evaluation: increment count
- `False` evaluation: nothing to do
%% Cell type:code id:e024c488 tags:
``` python
```
%% Cell type:markdown id:b9ff6434 tags:
### 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 `get_age` to retrieve lecture column value
- if: age is '' (empty), move on to next student using `continue`
- make sure to typecast return value to an integer
- 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's age is greater than previously known max age
- `True` evaluation: replace previously known max age with current age
- `False` evaluation: nothing to do
%% Cell type:code id:38bd778a tags:
``` python
```
%% Cell type:markdown id:b40a32fb tags:
### What is the age of the youngest student in current lecture (example: LEC001)?
- use similar algorithm as above question
%% Cell type:code id:ea77e0cd tags:
``` python
```
%% Cell type:markdown id:296c2a49 tags:
### What is the average age of students enrolled in CS220 / CS319?
- you will get an interesting answer :)
- how can we ensure that data doesn't skew statistics?
%% Cell type:code id:8b7c8367 tags:
``` python
for idx in range(project.count()):
age = project.get_age(idx)
if age == '':
continue
age = int(age)
print(age)
```
%% Cell type:markdown id:48f1c791 tags:
### 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
- 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:
``` python
```
%% 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?
%% Cell type:code id:fada2a40 tags:
``` python
```
%% Cell type:markdown id:68793d99 tags:
## Self-practice
%% Cell type:markdown id:2eeed867 tags:
### How many current lecture (example: LEC001) students are runners?
%% Cell type:markdown id:1ea57e12 tags:
### How many current lecture (example: LEC001) students are procrastinators?
%% Cell type:markdown id:cf0ac7c8 tags:
### How many current lecture (example: LEC001) students own or have owned a pet?
%% Cell type:markdown id:ffd5e10f tags:
### 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
%% Cell type:markdown id:f255b95a tags:
### 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
%% Cell type:markdown id:db60812c tags:
### Considering current lecture students (example: LEC001), is the first student with age 18 a runner?
%% Cell type:markdown id:70a8ac57 tags:
### 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?
%% Cell type:markdown id:581ea197 tags:
### 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?
%% Cell type:markdown id:5f943c98 tags:
### 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?
%% Cell type:markdown id:9b104a50 tags:
### 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?
%% Cell type:code id:fcee0994 tags:
``` python
```
%% Cell type:markdown id:dd1c3a1b tags:
# Iteration 1
# Iteration
## Readings:
### For Friday
- Chapter 7 of Think Python
- Chapter 6.1 to 6.3 of Python for Everybody
### For Monday
- Chapter 2 of Sweigart book
- Chapter 6.4 of Python for Everybody
%% Cell type:markdown id:595d2e5b tags:
## Learning Objectives:
- Implement an iterative algorithm using a `while` loop, for
- printing / counting
- validating user input
- performing an iterative calculation
- printing character art
- Trace iterative algorithms and determine their output
- Recognize common `while` loop errors
- Infinite loops (when unintentional)
- Off-by-one mistakes in the loop control variable
- Read and trace through Python code containing nested loops.
- Read and trace through Python code using `break` or `continue` in a `while` loop
- Determine the effect of break and continue in nested loops
%% Cell type:code id:c30a8ea2 tags:
``` python
# import statements
import time
import math
```
%% Cell type:markdown id:f113fc7b tags:
### Example 0: Simple countdowns
%% Cell type:markdown id:73959e77 tags:
**How to termination infinite loop in:**
- jupyter: Kernel > Interrupt (fix and then re-run)
- script mode / interactive mode: Ctrl + C (Kill signal)
%% Cell type:code id:cb8de263 tags:
``` python
#TODO: Copy/paste this example into PythonTutor
#Count from 0 to 3, printing each number
count = 0
while count <= 3:
print(count)
count += 1
```
%% Cell type:code id:23dbc9da tags:
``` python
#TODO: Copy/paste this example into PythonTutor
#Count from 3 to -3, printing each number
count = 3
while count >= -3:
print(count)
count -= 1
```
%% Cell type:markdown id:115e8742 tags:
### Example 1: Countdown timer alarm
%% Cell type:code id:42f4a48f tags:
``` python
# TODO: use input function to get user input for number of seconds
start = ???
# TODO: copy start into another variable
remaining = ???
while ???: # TODO: iterate from start to 1
print(remaining, "seconds left")
# TODO: update loop control variable's value to make progress towards terminating
# the loop, that is turning loop condition to False
remaining -= ???
# TODO: now run the cell to see the output. Didn't it go too fast?
# TODO: call time module sleep function, by passing 1 as argument
# TODO: print "BEEP BEEP BEEP ..." (10 BEEPS) without typing BEEP 10 times
# What string operator can you use here?
# wake up call
```
%% Cell type:markdown id:d54200ad tags:
## `for` loop
- another kind of loop
- does not require initialization of loop control variable outside the loop
- loop statement itself creates the loop control variable
- keywords `for` and `in`
### range built-in function
- accepts a single integer argument and produces a sequence of numbers from 0 to argument - 1, that is argument is exclusive
- accepts two integer arguments and produces a sequence of numbers from start (argument1) to end (argument2) - 1
%% Cell type:code id:43776615 tags:
``` python
for i in range(5): # single arugment -> produces 0, 1, 2, 3, and 4
print(i)
```
%% Cell type:code id:e3f01e6f tags:
``` python
for i in range(5, 10): # two arguments -> produces 5, 6, 7, 8, and 9
print(i)
```
%% Cell type:code id:b37a6842 tags:
``` python
# TODO: write a for loop to iterate over the numbers 2 to 8
```
%% Cell type:markdown id:558e4bed tags:
### Example 2: Print the square of all positive numbers <= 5
First, we show the code for how to do this with a while loop. Then, we'll work together to do the same thing with a for loop.
%% Cell type:code id:5ec1ba4f tags:
``` python
x = 1
while x <= 5:
print(str(x) + " squared is:")
print(str (x ** 2))
x += 1
print("all done!")
```
%% Cell type:code id:1de3a188 tags:
``` python
# TODO write a function using a for loop that prints the square of all positive numbers <= 5
# the output should be identical to the output of the cell above
```
%% Cell type:code id:9df8c834 tags:
``` python
# TODO what value does x have after the for loop finishes? What about after the while loop finishes?
```
%% Cell type:markdown id:cdc66ffa tags:
### Example 3: Find the max value of a function on an interval
<div>
<img src="attachment:Curve_peak.png" width="600"/>
</div>
%% Cell type:code id:2ec27141 tags:
``` python
def f(x):
return 5 - (x - 2) ** 2
print(f(1))
```
%% Cell type:code id:0098b6aa tags:
``` python
# TODO: for what value of x will f(x) produce the maximum y value?
print(f(???))
```
%% Cell type:code id:27298992 tags:
``` python
# Goal: find the x that maximizes the y = f(x)
# Let's try the values from -5 to 5
# Goal: after the loop, best_x and best_y should contain just that
# Try out increasing increments, make sure to comment the other increment
# delta_x = 1
# delta_x = 0.1
# delta_x = 0.01
# delta_x = 0.001
print("Best x:", best_x)
print("Best y:", best_y)
```
%% Cell type:markdown id:249f2aa7 tags:
### Example 4: Integration (Riemann Sum)
<div>
<img src="attachment:ReimannSum.png" width="600"/>
</div>
%% Cell type:code id:96b98336 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 = ??? # TODO: use f(x) defined previously
rect_area = ???
total_area += ???
current_x += delta_x
print("Area found using approximation is:", total_area)
```
%% Cell type:markdown id:3e8d609b tags:
### Example 5: Find primes
%% Cell type:code id:f2d0c381 tags:
``` python
def is_prime(num):
""" returns True if x is prime, false otherwise. Assumes x is positive"""
# try all divisors from 2 to sqrt(num) to check if num is prime
divisor = 2
while ???:
# check if num is divisible by divisor
if num % divisor == 0:
return False
divisor ???
return True
```
%% Cell type:code id:e7aea11c tags:
``` python
print(is_prime(1))
print(is_prime(2))
print(is_prime(3))
print(is_prime(7))
print(is_prime(16))
print(is_prime(23))
print(is_prime(1000000))
```
%% Cell type:code id:d26d790c tags:
``` python
print("Prime numbers:")
number = 2
# TODO: comment out this while loop and write equivalent for loop using range
while number <= 50:
if is_prime(number):
print(number, "is prime")
else:
print(number, "is not prime")
number += 1
```
%% Cell type:markdown id:0f29c848 tags:
## `break` and `continue`
`break` and `continue` are python keywords that let us end loop execution early
%% Cell type:markdown id:9dc76b8a tags:
### `break` example
- `break` enables to terminate execution of a while loop
- typically used with a conditional; that is you break when condition evaluates to `True`
%% Cell type:markdown id:81abdb38 tags:
def is_prime(num):
""" returns True if x is prime, false otherwise.
Assumes x is positive"""
# try all divisors from 2 to sqrt(num) to check if num is prime
divisor = ???
while ???:
# check if num is divisible by divisor
if num % divisor == ???:
return ???
divisor ???
return ???
%% Cell type:code id:e432722e tags:
``` python
print(is_prime(1))
print(is_prime(2))
print(is_prime(3))
print(is_prime(7))
print(is_prime(16))
print(is_prime(23))
print(is_prime(1000000))
```
%% Cell type:code id:c69150ed tags:
``` python
def has_prime(start, end):
# TODO: write a for loop using range, to:
# 1. iterate over every number from start to end
# 2. call is_prime function, to determine if it is prime
# 3. if you find at least one prime, has_prime should
# return True, False otherwise
pass
```
%% Cell type:code id:bd3e2027 tags:
``` python
has_prime(14, 16)
```
%% Cell type:code id:0429022b tags:
``` python
has_prime(1000000, 1001000)
```
%% Cell type:markdown id:32ba3308 tags:
### `continue` example
- `continue` enables to move on to the next iteration of the while loop
- typically used with a conditional; that is you continue when condition evaluates to `True`
%% Cell type:code id:cb569b21 tags:
``` python
# TODO: write an infinite loop using while
# TODO: get user input for age
# Goal: to compute running average
# It is easy to keep track of total and number of user
# inputs to compute running average
# TODO: discuss what is acceptable range for age
# What is the guinness world record for oldest person?
# TODO: discuss where you will initialize variables to keep track
# of total and number of user inputs so far and then type the
# computation lines to compute updated total and running average
# Now, try entering input as a large number outside of your
# acceptable age range. What happens to your average?
# TODO: handle this by writing a conditional and use continue,
# when user enters invalid age
# Finally, how do we terminate the infinite while loop
# Let's accept "q" as user input for termination
# TODO: handle that using another conditional
# Think carefully about where this conditional needs to be in
# terms of control flow
```
%% Cell type:markdown id:eb5bcba6 tags:
## After lecture practice
How many times is the while loop condition line executed?
%% Cell type:code id:1f48b50f tags:
``` python
n = 7
while n >= 5:
print(n)
n -= 1
# Answer is 4.
# Loop condition line always gets executed number of
# iterations + 1 times.
```
%% Cell type:markdown id:bb90cb11 tags:
Refactor the below function.
%% Cell type:code id:47a87068 tags:
``` python
def is_between(a, b, c):
"""Return True if b is between a and c (exclusive),
False otherwise"""
if a < c:
if a < b and b < c:
return True
else:
return False
elif c <= a:
if c < b and b < a:
return True
else:
return False
else:
return False
print(is_between(1, 3, 2)) # False
print(is_between(5, 11, 20)) # True
print(is_between(20, 3, 5)) # False
print(is_between(50, 11, 9)) # True
print(is_between(4, 4, 4)) # False
```
%% Cell type:code id:73f6ad82 tags:
``` python
def is_between_v2(a, b, c):
return ???
print(is_between_v2(1, 3, 2)) # False
print(is_between_v2(5, 11, 20)) # True
print(is_between_v2(20, 3, 5)) # False
print(is_between_v2(50, 11, 9)) # True
print(is_between_v2(4, 4, 4)) # False
```
%% Cell type:markdown id:11a9f3ce tags:
Trace the output without using Python interpreter
%% Cell type:code id:f0cac75c tags:
``` python
x = 1
while x < 5:
y = 1
while y < 10:
print (x * y, "\t", end="")
y += 1
print()
x += 1
```
%% Cell type:code id:eb1dc7f0 tags:
``` python
width = 9
height = 4
symbol = '#'
row = 0
while row < height:
col = 0
if row % 2 == 1:
print(" ", end="")
while col < width:
print(symbol + ' ', end="")
col += 1
# displays just a newline
print() # recall default value for end parameter is "\n"
row += 1
```
%% Cell type:code id:d572d8b0 tags:
``` python
```
......
__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_age(idx):
"""get_age(idx) returns the age of the student in row idx"""
return __student__[int(idx)]['Age']
def get_major(idx):
"""get_major(idx) returns the major of the student in row idx"""
return __student__[int(idx)]['Major']
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_latitude(idx):
"""get_latitude(idx) returns the latitude of the student's favourite place in row idx"""
return __student__[int(idx)]['Latitude']
def get_longitude(idx):
"""get_longitude(idx) returns the longitude of the student's favourite place in row idx"""
return __student__[int(idx)]['Longitude']
def get_piazza_topping(idx):
"""get_piazza_topping(idx) returns the preferred pizza toppings of the student in row idx"""
return __student__[int(idx)]['Pizza topping']
def get_pet_owner(idx):
"""get_pet_owner(idx) returns the pet preference of student in row idx"""
return __student__[int(idx)]['Pet preference']
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']
__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