Skip to content
GitLab
Explore
Sign in
Primary navigation
Search or go to…
Project
C
cs220-lecture-material
Manage
Activity
Members
Labels
Plan
Issues
Issue boards
Milestones
Iterations
Wiki
Requirements
Code
Merge requests
Repository
Branches
Commits
Tags
Repository graph
Compare revisions
Snippets
Locked files
Build
Pipelines
Jobs
Pipeline schedules
Test cases
Artifacts
Deploy
Releases
Package Registry
Container Registry
Model registry
Operate
Environments
Terraform modules
Monitor
Incidents
Service Desk
Analyze
Value stream analytics
Contributor analytics
CI/CD analytics
Repository analytics
Code review analytics
Issue analytics
Insights
Model experiments
Help
Help
Support
GitLab documentation
Compare GitLab plans
Community forum
Contribute to GitLab
Provide feedback
Keyboard shortcuts
?
Snippets
Groups
Projects
Show more breadcrumbs
CDIS
Computer Sciences
Courses
CS220
cs220-lecture-material
Commits
ff1ffc6d
Commit
ff1ffc6d
authored
1 year ago
by
Anna Meyer
Browse files
Options
Downloads
Patches
Plain Diff
lec 6 materials
parent
6f136e8a
No related branches found
No related tags found
No related merge requests found
Changes
2
Hide whitespace changes
Inline
Side-by-side
Showing
2 changed files
sum23/lecture_materials/06_Iteration1/06_Iteration-1.pdf
+0
-0
0 additions, 0 deletions
sum23/lecture_materials/06_Iteration1/06_Iteration-1.pdf
sum23/lecture_materials/06_Iteration1/lec_06_Iteration_1_template.ipynb
+425
-0
425 additions, 0 deletions
...materials/06_Iteration1/lec_06_Iteration_1_template.ipynb
with
425 additions
and
0 deletions
sum23/lecture_materials/06_Iteration1/06_Iteration-1.pdf
0 → 100644
+
0
−
0
View file @
ff1ffc6d
File added
This diff is collapsed.
Click to expand it.
sum23/lecture_materials/06_Iteration1/lec_06_Iteration_1_template.ipynb
0 → 100644
+
425
−
0
View file @
ff1ffc6d
{
"cells": [
{
"attachments": {},
"cell_type": "markdown",
"id": "dd1c3a1b",
"metadata": {},
"source": [
"# Iteration 1\n",
"\n",
"## Readings:\n",
"\n",
"- Chapter 7 of Think Python\n",
"- Chapter 6.1 to 6.3 of Python for Everybody"
]
},
{
"attachments": {},
"cell_type": "markdown",
"id": "595d2e5b",
"metadata": {},
"source": [
"## Learning Objectives:\n",
"\n",
"- Implement an iterative algorithm using a `while` loop, for\n",
" - printing / counting\n",
" - validating user input\n",
" - performing an iterative calculation\n",
" - printing character art\n",
"\n",
"- Trace iterative algorithms and determine their output\n",
"\n",
"- Recognize common `while` loop errors\n",
" - Infinite loops (when unintentional)\n",
" - Off-by-one mistakes in the loop control variable"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c30a8ea2",
"metadata": {},
"outputs": [],
"source": [
"# import statements\n",
"\n",
"import time\n",
"import math"
]
},
{
"attachments": {},
"cell_type": "markdown",
"id": "f113fc7b",
"metadata": {},
"source": [
"### Example 0: Simple countdowns"
]
},
{
"attachments": {},
"cell_type": "markdown",
"id": "73959e77",
"metadata": {},
"source": [
"**How to termination infinite loop in:**\n",
"- jupyter: Kernel > Interrupt (fix and then re-run)\n",
"- script mode / interactive mode: Ctrl + C (Kill signal)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "cb8de263",
"metadata": {},
"outputs": [],
"source": [
"#TODO: Copy/paste this example into PythonTutor\n",
"#Count from 0 to 3, printing each number\n",
"count = 0\n",
"\n",
"while count <= 3:\n",
" print(count)\n",
" count += 1"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "23dbc9da",
"metadata": {},
"outputs": [],
"source": [
"#TODO: Copy/paste this example into PythonTutor\n",
"#Count from 3 to -3, printing each number\n",
"count = 3\n",
"\n",
"while count >= -3:\n",
" print(count)\n",
" count -= 1"
]
},
{
"attachments": {},
"cell_type": "markdown",
"id": "115e8742",
"metadata": {},
"source": [
"### Example 1: Countdown timer alarm"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "42f4a48f",
"metadata": {},
"outputs": [],
"source": [
"# TODO: use input function to get user input for number of seconds\n",
"start = ???\n",
"\n",
"# TODO: copy start into another variable\n",
"remaining = ???\n",
"while ???: # TODO: iterate from start to 1\n",
" print(remaining, \"seconds left\")\n",
" # TODO: update loop control variable's value to make progress towards terminating \n",
" # the loop, that is turning loop condition to False\n",
" remaining -= ???\n",
" # TODO: now run the cell to see the output. Didn't it go too fast?\n",
" # TODO: call time module sleep function, by passing 1 as argument\n",
"\n",
"# TODO: print \"BEEP BEEP BEEP ...\" (10 BEEPS) without typing BEEP 10 times\n",
"# What string operator can you use here?\n",
"\n",
"\n",
"# wake up call"
]
},
{
"attachments": {},
"cell_type": "markdown",
"id": "d54200ad",
"metadata": {},
"source": [
"## `for` loop\n",
"\n",
"- another kind of loop\n",
"- does not require initialization of loop control variable outside the loop\n",
"- loop statement itself creates the loop control variable\n",
"- keywords `for` and `in`\n",
"\n",
"### range built-in function\n",
"- accepts a single integer argument and produces a sequence of numbers from 0 to argument - 1, that is argument is exclusive\n",
"- accepts two integer arguments and produces a sequence of numbers from start (argument1) to end (argument2) - 1"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "43776615",
"metadata": {},
"outputs": [],
"source": [
"for i in range(5): # single arugment -> produces 0, 1, 2, 3, and 4\n",
" print(i)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "e3f01e6f",
"metadata": {},
"outputs": [],
"source": [
"for i in range(5, 10): # two arguments -> produces 5, 6, 7, 8, and 9\n",
" print(i)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b37a6842",
"metadata": {},
"outputs": [],
"source": [
"# TODO: write a for loop to iterate over the numbers 2 to 8\n"
]
},
{
"attachments": {},
"cell_type": "markdown",
"id": "558e4bed",
"metadata": {},
"source": [
"### Example 2: Print the square of all positive numbers <= 5\n",
"\n",
"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",
"execution_count": null,
"id": "5ec1ba4f",
"metadata": {},
"outputs": [],
"source": [
"x = 1\n",
"while x <= 5:\n",
" print(str(x) + \" squared is:\")\n",
" print(str (x ** 2))\n",
" x += 1\n",
"print(\"all done!\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "1de3a188",
"metadata": {},
"outputs": [],
"source": [
"# TODO write a function using a for loop that prints the square of all positive numbers <= 5\n",
"# the output should be identical to the output of the cell above\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "9df8c834",
"metadata": {},
"outputs": [],
"source": [
"# TODO what value does x have after the for loop finishes? What about after the while loop finishes?\n"
]
},
{
"attachments": {},
"cell_type": "markdown",
"id": "cdc66ffa",
"metadata": {},
"source": [
"### Example 3: Find the max value of a function on an interval\n",
"\n",
"<div>\n",
"<img src=\"attachment:Curve_peak.png\" width=\"600\"/>\n",
"</div>"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "2ec27141",
"metadata": {},
"outputs": [],
"source": [
"def f(x):\n",
" return 5 - (x - 2) ** 2\n",
" \n",
"print(f(1))"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "0098b6aa",
"metadata": {},
"outputs": [],
"source": [
"# TODO: for what value of x will f(x) produce the maximum y value?\n",
"print(f(???))"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "27298992",
"metadata": {},
"outputs": [],
"source": [
"# Goal: find the x that maximizes the y = f(x)\n",
"\n",
"# Let's try the values from -5 to 5\n",
"\n",
"# Goal: after the loop, best_x and best_y should contain just that\n",
"\n",
"# Try out increasing increments, make sure to comment the other increment\n",
"# delta_x = 1\n",
"# delta_x = 0.1\n",
"# delta_x = 0.01\n",
"# delta_x = 0.001\n",
"\n",
"\n",
"\n",
"print(\"Best x:\", best_x)\n",
"print(\"Best y:\", best_y)"
]
},
{
"attachments": {},
"cell_type": "markdown",
"id": "249f2aa7",
"metadata": {},
"source": [
"### Example 4: Integration (Riemann Sum)\n",
"\n",
"<div>\n",
"<img src=\"attachment:ReimannSum.png\" width=\"600\"/>\n",
"</div>"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "96b98336",
"metadata": {},
"outputs": [],
"source": [
"# Let's try the values from 1 to 5\n",
"start_x = 1\n",
"end_x = 5\n",
"total_area = 0\n",
"current_x = start_x\n",
"# Try out increasing values of width, make sure to comment the other width values\n",
"# delta_x = 1\n",
"delta_x = 0.1\n",
"# delta_x = 0.01\n",
"# delta_x = 0.001\n",
"\n",
"while current_x <= end_x:\n",
" y = ??? # TODO: use f(x) defined previously\n",
" rect_area = ???\n",
" total_area += ???\n",
" current_x += delta_x\n",
" \n",
"print(\"Area found using approximation is:\", total_area)"
]
},
{
"attachments": {},
"cell_type": "markdown",
"id": "3e8d609b",
"metadata": {},
"source": [
"### Example 5: Find primes"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "f2d0c381",
"metadata": {},
"outputs": [],
"source": [
"def is_prime(num):\n",
" \"\"\" returns True if x is prime, false otherwise. Assumes x is positive\"\"\"\n",
" \n",
" # try all divisors from 2 to sqrt(num) to check if num is prime\n",
" divisor = 2\n",
" while ???:\n",
" # check if num is divisible by divisor\n",
" if num % divisor == 0:\n",
" return False\n",
" divisor ???\n",
" \n",
" return True"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "e7aea11c",
"metadata": {},
"outputs": [],
"source": [
"print(is_prime(1))\n",
"print(is_prime(2))\n",
"print(is_prime(3))\n",
"print(is_prime(7))\n",
"print(is_prime(16))\n",
"print(is_prime(23))\n",
"print(is_prime(1000000))"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "d26d790c",
"metadata": {},
"outputs": [],
"source": [
"print(\"Prime numbers:\")\n",
"number = 2\n",
"# TODO: comment out this while loop and write equivalent for loop using range\n",
"while number <= 50: \n",
" if is_prime(number):\n",
" print(number, \"is prime\")\n",
" else:\n",
" print(number, \"is not prime\")\n",
" number += 1"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.6"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
%% Cell type:markdown id:dd1c3a1b tags:
# Iteration 1
## Readings:
-
Chapter 7 of Think Python
-
Chapter 6.1 to 6.3 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
%% 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
```
This diff is collapsed.
Click to expand it.
Preview
0%
Loading
Try again
or
attach a new file
.
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Save comment
Cancel
Please
register
or
sign in
to comment