Title: IS 313: Putting loops to work for you
1IS 313 Putting loops to work for you
-35, -24, -13, -2, 9, 20, 31, ?
26250, 5250, 1050, 210, ?
and which one is not like the others ?
What's next?
1, 11, 21, 1211, 111221, ?
2, 22, 222, ?
90123241791111 , 93551622, 121074, 3111, ?
- Thinking loopily and
cumulatively
sounds natural enough to me!
for a while
2Schedule
9/27 Loops, some graphics, and webapps
9/28 Homework 2 due
10/4 Maximizing and webforms
10/5 Homework 3 due
10/11 Language-processing on the web?
10/12 Homework 4 due
10/18 No class this day!
10/29 No HW due this day!
10/25 Objects small projects
10/26 Homework 5 due
3Self-altering statements?
recursion is worse!
Shortcuts for changing variables
or, even shortcuttier
age 41 age age 1
age 1
amoebas 100000 amoebas amoebas 2 hwToGo
8 hwToGo hwToGo - 1 u235 10000000000000 u235
u235 / 2
4fore!
for x in range(8) print 'x is', x print
'Phew!'
anatomy? empty? x unused?
5fore!
x is assigned each value from this sequence
1
for x in range(8) print 'x is', x print
'Phew!'
3
LOOP back to step 1 for EACH value in the list
the BODY or BLOCK of the for loop runs with that x
2
anatomy? empty? x unused?
Code AFTER the loop will not run until the loop
is finished.
4
6four on for
for x in range(8) print 'x is', x
how about 6x? sum the list? construct the list?
7Accumulating an answer
Finding the sum of a list
def sum( L ) """ returns the sum of L's
elements """ sum 0 for x in L
sum sum x return sum
Accumulator!
Liar! That's not the sum!
shortcuts? vs. recursion? sum every OTHER
element?
8for loops selfless vs. selfish
Element-based Loops
sum 0 for x in L sum x
L 42, -10, 4
x
"selfless"
9for loops selfless vs. selfish
Element-based Loops
Index-based Loops
sum 0 for x in L sum x
sum 0 for i in sum
i
0
1
2
L 42, -10, 4
L 42, -10, 4
x
these index-based loops seem so egocentric
10for loops selfless vs. selfish
Element-based Loops
Index-based Loops
sum 0 for x in L sum x
sum 0 for i in range(len(L)) sum Li
i
0
1
2
L 42, -10, 4
L 42, -10, 4
x
Li
11Perspective on for loops
At the top of a project file
// Author Matt Beaumont // Purpose To get me
out of CS... // ...no, really... //
Purpose To create and maintain a list //
of films and directors / Notes I haven't
liked for-loops since the day I met them. They
bother me for some reason. Hence, no for-loops
/
and it is possible to avoid them entirely
12Extreme Looping
What does this code do?
print 'It keeps on' while True print 'going
and' print 'Phew! I\'m done!'
13Extreme Looping
Anatomy of a while loop
the loop keeps on running as long as this test is
True
print 'It keeps on' while True print 'going
and' print 'Phew! I\'m done!'
while loop
This won't print until the while loop finishes -
in this case, never!
alternative tests?
14Making our escape!
import random escape 0 while escape ! 42
print 'Help! Let me out!' escape
random.choice(41,42,43) print 'At last!'
how could we count the number of loops we run?
how could we make it easier/harder to escape?
15Procrastination Programming
Every while loop can be a while True loop!
- just be sure to break!
16Robot Loops?!
Robots run programs that are variants of this
very basic loop
while True sense() plan() act()
This is the "spa" architecture it's almost
universal.
Which of those three pieces is the most
difficult!?
Robot of the Day...
How to escape ?
17Give me a break !
import random escape 0 while True print
'Help! Let me out!' escape
random.choice(41,42,43) if escape 42
break print 'At last!'
I'll figure out later how to get out of this loop!
OK I'll stop the loop now and continue with the
code after the loop
compare return
18Loops aren't just for lists
for c in 'down with CS!' print c
19def cc( s )
Write a loop to find and return the min of a
list, L
n 0 for c in s if c not in 'aeiou' n
1 return n
L is a list of numbers.
def mymin( L )
how could you "accumulate" the minimum?
What does this return?
gtgtgt cc( 'forty-two' )
def odd( N )
Extra!
steps 0
while N gt 1 if N20 N / 2 else
N 3N1
steps 1
return steps
What does this return?
gtgtgt odd( 3 )
20What does this return?
def cc( s )
n 0 for c in s if c not in 'aeiou' n
1 return n
gtgtgt cc( 'forty-two' )
21Extra!
def odd( N )
steps 0
while N gt 1 if N20 N / 2 else
N 3N1
steps 1
return steps
gtgtgt odd( 3 )
22L is a list of numbers.
def min( L )
23Homework 3
Hooray Sanity!
Sequences
2
one note on these...
What is this stuff?
or you could be saying both
Sound
3
Graphics
4
24Look-And-Say Sequences(aka Read-It-And-Weep)
str versus float or int
1 11 21 1211 111221 312211 ?
When does the first 4 appear?
25Homework 3
Sequences
2
or you could be saying both
Sound
3
DEMO!
Graphics
4
26Representing Sound
physics
continuous plot of air pressure vs. time
sampling
samples taken every 1/22050th of a second
quantization
Each sample is measured on a scale from -32,768
to 32,767. (This fits into 2 bytes.)
storage
These two bytes are called a frame. Raw audio
data - such as what is written to the surface of
a CD - is simply a list of these frames.
pulse code modulation PCM data
27Homework 3
Sequences
2
or you could be saying both
Sound
3
DEMO!
Graphics
4
28Etch-a-Sketch ?
www.gvetchedintime.com
No way this is real but it is !
29Python's Etch-a-Sketch
Be SURE to start IDLE with "no subprocess"
Mac instructions...
Windows instructions...
(Step 1) Go to the Start menu's search field
(Step 1) menus Go Utilities Terminal
Start this!
(Step 2) Type or paste the full path to IDLE
If you used the standard install, it will be
C\Python27\Lib\idlelib\idle.pyw -n
(Step 2) Enter idle n
Hit return you'll see a console window and IDLE
open.
Then, you can type
from turtle import
30Python's Etch-a-Sketch
from turtle import
Turtle Canvas
reset() left(90) forward(50) right(90) backward(50
) down() or up() color('green') tracer(1) or
tracer(0) width(5) and lots more!
degrees!
(42,42)
states if the pen draws or not
(0,0)
window_height()
states if the pen animates or not
window_width()
www.cs.hmc.edu/twiki/bin/view/CS5/TurtleDirections
for turtle installation and help
31Recursive Graphics
there is no tri
Could we tri this with recursion?
(1)
def tri() """ draws a polygon """
forward(100) left(120) forward(100)
left(120) forward(100) left(120)
def tri( ) """ draws a polygon """
Could we create any regular n-gon?
(2)
I don't know about tri, but there sure's NO
return !
32Turtle Graphics
Name(s)
Finish rwalk to draw a "stock-market-type" random
path of nsteps steps. Use recursion!
What does chai draw?
(1)
(2)
from random import def rw(nsteps) """
moving for nsteps steps, randomly 45
deg. left/up or right/down """ if nsteps
0 return if choice('left','right')
'left' else 'right'
def chai(size) """ mystery! """
forward(size) left(90) forward(size/2.0)
right(90) right(90) forward(size)
left(90) left(90) forward(size/2.0)
right(90) backward(size)
Ex Cr How could you make it a bull (or a bear)
market?
one possible result of rw(20)
33What does chai draw?
(1)
def chai(size) """ mystery! """
forward(size) left(90) forward(size/2.0)
right(90) right(90) forward(size)
left(90) left(90) forward(size/2.0)
right(90) backward(size)
Why are there two identical commands in a row?
How could you add more to each end?
34Finish rwalk to draw a "stock-market-type" random
path of nsteps steps.
(2)
from random import def rw(nsteps) """
moving for nsteps steps, randomly 45
deg. left/up or right/down """ if nsteps
0 return if choice('left','right')
'left' else 'right'
one possible result of rw(20)
Ex Cr How could you make it a bull (or a bear)
market?
What if we didn't turn back to face forward each
time?
35hw3pr4 spiral
81
72.9
90
close-up of innermost part of the spiral
spiral( 100, 90, 0.9 )
100
spiral( initLength, angle, multiplier )
36hw3pr4 svTree
Level 1
Level 2
Level 3
Level 4
svTree( 100, 4 )
I wonder what happened to the leaves on that
tree ?
svTree( trunkLength, levels )
37hw2pr3 spiral
81
72.9
90
close-up of innermost part of the spiral
spiral( 100, 90, 0.9 )
100
spiral( initLength, angle, multiplier )
38hw2pr3 svTree
Level 1
Level 2
Level 3
Level 4
svTree( 100, 4 )
I wonder what happened to the leaves on that
tree ?
svTree( trunkLength, levels )
39The Koch curve
snowflake( 100, 0 )
snowflake( 100, 1 )
snowflake( 100, 2 )
snowflake( 100, 3 )
snowflake( 100, 4 )
snowflake( 100, 5 )
40CGI Python Web
a very common technology for webapplications is
the Common Gateway Interface or CGI
Apache
Firefox
Python
This week
Last week
Next week
Next week
webserver
browser
any programs!
41CGI Python Web
Basic idea
Your Python file prints the HTML page you want!
!C/Python27/python.exe import cgi import
cgitb cgitb.enable() print "Content-Type
text/html \ charsetISO-8859-1\n\n" print print
""" lthtmlgt ltbodygt lth1gtHello from
Python!lt/h1gt lt/bodygt lt/htmlgt """
This week
Python
CGI
42Lab/HW time
I will be happy to help get your webserver
running Python scripts. That will help a lot
with problem 1!
Have fun!
43(No Transcript)
44Monty Hall
Lets make a deal 63-86
Sept. 1990
inspiring the Monty Hall paradox
45Monty Hall
Getting the user's input
answer raw_input( 'What is your name?' )
door input( 'Which door do you choose?' )
response raw_input( 'Switch or stay?' )
Making decisions
if response 'switch'
print 'So you switch to door', other_door
But how to get the "other door" ?
46Seeing into the future
def menu() """ prints our menu of options
""" print "(1) Input a list of numbers"
print "(2) Guess the next element" print "(9)
Quit"
def seer() """ handles user input for our
menu """ while True menu()
uc input('Which option? ') print 'The
inner eye does not see upon command!'
47Clearer Vision
def seer() """ handles user input for our
menu """ while True menu()
uc input('Which option? ') print 'The
inner eye does not see upon command!' if uc
48the gift
LightPath, September 1999
49watching the charts
LightPath, six months later
50"brokerage" seems apt
LightPath, now
51T. T. Securities (TTS)
Input stock prices for a number of days in a
row, and then analyze that data .
52T. T. Securities (TTS)
Input stock prices for a number of days in a
row, and then analyze that data .
Menu
(0) Input a new list (1) Print the current
list (2) Find the average price (3) Find the
standard deviation (4) Find the min and its
day (5) Find the max and its day (6) Your TTS
investment plan (9) Quit Enter your choice
Software
53Functions
There are a number of formulas, but we will use
this one
functions
def average( L )
def stdev( L )
Menu
def mini( L )
(0) Input a new list (1) Print the current
list (2) Find the average price (3) Find the
standard deviation (4) Find the min and its
day (5) Find the max and its day (6) Your TTS
investment plan (9) Quit Enter your choice
def maxi( L )
54Standard Deviation
There are a number of formulas, but we will use
this one
functions
Menu
def stdev( L )
(0) Input a new list (1) Print the current
list (2) Find the average price (3) Find the
standard deviation (4) Find the min and its
day (5) Find the max and its day (6) Your TTS
investment plan (9) Quit Enter your choice
?
(Li - Lav)2
i
len(L)
55T. T. Securities (TTS)
Investment analysis for the 21st century
Hardware
Menu
(0) Input a new list (1) Print the current
list (2) Find the average price (3) Find the
standard deviation (4) Find the min and its
day (5) Find the max and its day (6) Your TTS
investment plan (9) Quit Enter your choice
Software
56T. T. Securities (TTS)
Investment analysis for the 21st century
Hardware
Menu
(0) Input a new list (1) Print the current
list (2) Find the average price (3) Find the
standard deviation (4) Find the min and its
day (5) Find the max and its day (6) Your TTS
investment plan (9) Quit Enter your choice
Software
57The TTS advantage!
Your stock's prices
L 40, 80, 10, 30, 27, 52, 5, 15
The TTS investment strategy
Day Price 0 40.0 1 80.0 2 10.0 3
30.0 4 27.0 5 52.0 6 5.0 7 15.0
but, you must sell after you buy.
58Example
Alter this code to return the index of L's
minimum.
gtgtgt minday( 9,8,1,7 ) 2
def minday( L ) min L0 for x in L
if x lt min min x return x
min-value loop
59Example
Alter this code to return the index of L's
minimum.
gtgtgt minday( 9,8,1,7 ) 2
def minday( L ) min L0 for
if lt min min
return
using an index-based loop
INDEX-BASED LOOP
60What does this code print?
for x in range(3) for y in range(3) print
x, y
61Example
for x in range(3) for y in range(3) print
x, y
Hint adapt this code
gtgtgt diff( 7,3,0,6 ) 1
Return the minimum difference between one value
from X and one value from Y.
Only consider unsigned differences.
def diff( X, Y )
X and Y will be lists of numbers
62Lab Questions
63Extra (!) funky series
- Harmonic Sequence
- 1/1 1/2 1/3 1/4 1/5 1/6
- Without composites (primes only)
- 1/1 1/2 1/3 1/4 1/5 1/6 1/7
- Without 9s
- 1/1 1/2 1/8 1/9 1/18 1/19
1/88 1/89 1/90 1/91
Diverges!
???
???
64Monte Carlo p
Hw8 Pr3
A engineering challenge to estimate p using
everyday items...
65Easy as p
(1,1)
Visualize
(-1,-1)
66iPhone, geohot, and Von Neumann
George Hotz's iPhone
Before
After
In red one memory-access bit
soldered to be 1.8v (1)
67iPhone, geohot, and Von Neumann
When starting up, the phone checks 4 locations in
memory to see if its software is already there.
Only if it sees the software is NOT there, does
the phone use software from general-purpose
memory to start. Otherwise, it loads its software
from read-only memory.
binary
hex
10100000000000000000000000110000 10100000000000001
010010110100000 10100000000000010101110001011000 1
0100000000000010111001101110000
0xA0000030 0xA000A5A0 0xA0015C58 0xA0017370
George Hotz's iPhone
The 4 32-bit memory locations it checks are
1
There's not much you can do to change what is in
those areas of read-only memory. Instead, the
idea was to change one of the address lines to be
high while it checked these four locations.
10100000000001000000000000110000 10100000000001001
010010110100000 10100000000001010101110001011000 1
0100000000001010111001101110000
The memory locations it actually checks are thus
All of these locations are in a read/write
(accessible) portion of the phone's memory -- so,
they can be written to the "reset" signal. This
reloads the phone's start-up software from
read/write memory -- allowing arbitrary network
access, not just ATT.
68iPhone, geohot, and Von Neumann
George Hotz's iPhone
the trade
69Quiz
Finish these two methods
- This method returns the sum of the elements in
the input array.
public static double sum(double A) double
s 0.0 for ( return
s
- This method returns the average of the elements
in the input array.
public static double average(double A)
Extra Credit How concise can this method be?
70- This method returns the maximum element from the
input array.
public static double max(double A)
Extra What is something unusual and unrelated
to CS 5 that you the person next to you have
in common ?!
71Loopy thinking
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
s 'gattacaaggtaaaatgca'
How could we find the number of 'a's ? How about
'a's and 't's?
How could we find the number of 'ta's ?
How could we find the longest sequence of 'a's ?
72Loopy thinking
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
s 'gattacaaggtaaaatgca'
s 'gattacaaggtaaaatgca' N 0 for i in
range(0,len(s)) if si 'a' N
N 1 print 'N is', N
How could we find the number of 'a's ? How about
'a's and 't's?
How could we find the number of 'ta's ?
How could we find the longest sequence of 'a's ?
73Loopy thinking
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
s 'gattacaaggtaaaatgca'
s 'gattacaaggtaaaatgca' N 0 for i in
range(0,len(s)) if si 'a' or si
't' N N 1 print 'N is', N
How could we find the number of 'a's ? How about
'a's and 't's?
How could we find the number of 'ta's ?
How could we find the longest sequence of 'a's ?
74Loopy thinking
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
s 'gattacaaggtaaaatgca'
s 'gattacaaggtaaaatgca' N 0 for i in
range(1,len(s)) if si 'a' and si-1
't' N N 1 print 'N is', N
How could we find the number of 'a's ? How about
'a's and 't's?
How could we find the number of 'ta's ?
How could we find the longest sequence of 'a's ?
75Loopy thinking
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
s 'gattacaaggtaaaatgca'
How could we find the longest sequence of 'a's ?
76Planning in "pseudocode"
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
s 'gattacaaggtaaaatgca'
Keep track of CurRun, MaxRun
Loop through the string
if we do see an 'a'
if the PREVIOUS letter is NOT an 'a'
if the PREVIOUS letter IS an 'a'
77Planning in "pseudocode"
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
s 'gattacaaggtaaaatgca'
Keep track of CurRun, MaxRun
Loop through the string
if we do see an 'a'
if the PREVIOUS letter is NOT an 'a'
Start a Run! CurRun 1
if the PREVIOUS letter IS an 'a'
Continue our run! CurRun CurRun 1
Check for a new maximum
78Planning in "pseudocode"
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
s 'gattacaaggtaaaatgca'
MAX 0 cur 0 for i in range(0,len(s)) if
si 'a' if si-1 ! 'a'
cur 1 else cur cur
1 if cur gt MAX MAX
cur print 'Max is', MAX
Keep track of CurRun, MaxRun
Loop through the string
if we do see an 'a'
if the PREVIOUS letter is NOT an 'a'
Start a Run!
if the PREVIOUS letter IS an 'a'
Continue our run!
Check for a new maximum
79Challenge
Print the first N numbers in this series
Example
gtgtgt fib(11)
1 1 2 3 5 8 13 21 34 55 89
80Write any loop to print the first N terms of
Write an index-based loop to print the first N
terms of
N terms total
N terms total
0 1 2 3 6 7 14 15 30
7 9 11 13 15 17
def seven(N) for i in range(N)
feel free to add an accumulator, if you'd like!
Quiz, part 2
81input vs. raw_input
reply raw_input('Enter a string and I\'ll tell
you what I see.') for c in reply print 'I
see a(n) ', c
interprets what the user types as a string of
characters
reply input('Enter any list and I\'ll tell you
what I see.') for c in reply print 'I see
a(n) ', c
processes what the user types just as python would
82Why Assembly Language ?
Its only the foolish that never climb Mt. Fuji
-- or that climb it again.
Who writes most of the assembly language used?
83the compiler
a program that translates from human-usable
language into assembly language and machine
langauge
0000 0001 0000 0001
Compiler
1000 0010 0001 0001
0110 0010 0010 0001
0000 0010 0000 0010
0000 0000 0000 0000
x 6 y 7 z xy print z
loadn r1 6 loadn r2 7 mul r3 r1 r2 write r3
executable machine code
assembly or byte-code
the code
0000 0001
0010 0001
0110 0010
Interpreter
1000 0001
machine code
interpreting byte code
84Register r0 is always 0.
85Pure jumps not allowed!
Assembly language
Fortran, C, C, Basic,
GOTO
jump
86Who writes asembly?
I think the question is, "Who can spell assembly?"
people who need to talk to the processors
directly
87 Von Neumann Architecture
instructions executed here
programs stored here
CPU
RAM
Von Neumann bottleneck
random access memory
central processing unit
the bus!
0
Program Counter
read r1
Holds address of the next instruction
1
loadn r2 1
Instruction Register
Holds the current instruction
2
mul r2 r2 r1
3
addn r1 -1
0
r0
4
jgtz r1 2
16 registers, each 16 bits
5
write r2
r1
they can hold values from -32768 upto 32767
6
halt
r2
255
r15
factorial program
88iPhone, geohot, and Von Neumann
George Hotz's iPhone
89iPhone, geohot, and Von Neumann
George Hotz's iPhone
Before
In red one memory-access bit
90iPhone, geohot, and Von Neumann
When starting up, the phone checks 4 locations in
memory to see if its software is already there.
Only if it sees the software is NOT there, does
the phone use software from general-purpose
memory to start. Otherwise, it loads its software
from read-only memory.
binary
hex
10100000000000000000000000110000 10100000000000001
010010110100000 10100000000000010101110001011000 1
0100000000000010111001101110000
0xA0000030 0xA000A5A0 0xA0015C58 0xA0017370
George Hotz's iPhone
The 4 32-bit memory locations it checks are
There's not much you can do to change what is in
those areas of read-only memory. Instead, the
idea was to change one of the address lines to be
high while it checked these four locations.
91iPhone, geohot, and Von Neumann
George Hotz's iPhone
Before
After
In red one memory-access bit
soldered to be 1.8v (1)
92iPhone, geohot, and Von Neumann
When starting up, the phone checks 4 locations in
memory to see if its software is already there.
Only if it sees the software is NOT there, does
the phone use software from general-purpose
memory to start. Otherwise, it loads its software
from read-only memory.
binary
hex
10100000000000000000000000110000 10100000000000001
010010110100000 10100000000000010101110001011000 1
0100000000000010111001101110000
0xA0000030 0xA000A5A0 0xA0015C58 0xA0017370
George Hotz's iPhone
The 4 32-bit memory locations it checks are
1
There's not much you can do to change what is in
those areas of read-only memory. Instead, the
idea was to change one of the address lines to be
high while it checked these four locations.
10100000000001000000000000110000 10100000000001001
010010110100000 10100000000001010101110001011000 1
0100000000001010111001101110000
The memory locations it actually checks are thus
All of these locations are in a read/write
(accessible) portion of the phone's memory -- so,
they can be written to the "reset" signal. This
reloads the phone's start-up software from
read/write memory -- allowing arbitrary network
access, not just ATT.
93iPhone, geohot, and Von Neumann
George Hotz's iPhone
the trade
94Thinking about Hmmm
- Functions (and recursion) pretend to have a
separate processor on which to work
- Repeated actions occur through jumps
r1
19
- Results can be set, reset, and accumulated
23
42
r2
add r2 r2 r1
95Thinking about Hmmm
- Functions (and recursion) pretend to have a
separate processor on which to work
"Functional" Programming
Examples
results from composing individual
functions recursion is common abstraction allows
humans to think about 1 thing at a time
Fast matrix multiplication Fast median
finding Fast Fourier Transform
I may be seeing the theme here
96Thinking about Hmmm
- Functions (and recursion) pretend to have a
separate processor on which to work
"Functional" Programming
"Imperative" Programming
Python processor. variables
registers accumulation is common jumps loops
require people to do the work of the stack
results from composing individual
functions recursion is common abstraction allows
humans to think about 1 thing at a time
You mean this is NON-functional programming?!?
97Input and typing
meters raw_input('How many m? ') cm meters
100 print 'That is', cm, 'cm.'
What is python thinking ?!?
I'm thinking I like these units better then light
years per year!
98Fix 1 use a type converter
meters float(raw_input('How many m? ')) cm
meters 100 print 'That is', cm, 'cm.'
check out my newly installed float converter!
1.0
100.0
The type of variable (box) matters!
name meters type float
name cm type float
99Homework 3
Sequences
1
Hooray Sanity!
What is this stuff?
Graphics
2
or you could be saying both
100Fix 2 use input()
gets processed input from user meters
input('How many m? ') cm meters 100 print
'That is', cm, 'cm.'
I always use input -- but don't quote me on that.
101Fix 2 use input()
gets processed input from user meters
input('How many m? ') cm meters 100 print
'That is', cm, 'cm.'
I always use input -- but don't quote me on that.
raw_input always returns input as a string!
input processes the input as if typed into Python
both allow you to specify a prompt string