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/30/09 Graphics and loops!
10/1/07 Homework 2 due
10/7/09 Maximizing and browser apps
10/8/07 Homework 3 due
10/14/09 Language-processing on the web
10/15/07 Homework 4 due - small webapp
10/21/09 Fall break!
10/22/07 No HW due
10/28/09 Objects larger projects
10/29/07 Homework 5 due
3Self-altering statements?
recursion is worse!
Shortcuts for changing variables
or, even shortcuttier
age 40 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?
15Loops aren't just for lists
for c in 'down with CS!' print c
16def cc( s )
n 0 for c in s if c not in 'aeiou' n
1 return n
Write a loop to find and return the min of a
list, L
L is a list of numbers.
def min( L )
how could you "accumulate" the minimum?
gtgtgt cc( 'forty-two' )
What do these two f'ns return?
def odd( N )
steps 0
while N gt 1 if N20 N / 2 else
N 3N1
steps 1
return steps
gtgtgt odd( 3 )
17What do these two f'ns return?
def cc( s )
n 0 for c in s if c not in 'aeiou' n
1 return n
gtgtgt cc( 'forty-two' )
18What do these two f'ns return?
def odd( N )
steps 0
while N gt 1 if N20 N / 2 else
N 3N1
steps 1
return steps
gtgtgt odd( 3 )
19def min( L )
L is a list of numbers.
20Homework 3
Hooray Sanity!
Sequences
1
What is this stuff?
or you could be saying both
Graphics
2
21Look-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?
22Input 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!
23Fix 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
24Fix 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.
25Fix 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
26Procrastination Programming
Every while loop can be a while True loop!
- just be sure to break!
27Give 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
28Homework 3
Sequences
1
Hooray Sanity!
What is this stuff?
Graphics
2
or you could be saying both
29Python's Etch-a-Sketch
from turtle import
or wynnturtle
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!
states if the pen draws or not
states if the pen animates or not
A new human-computer interface?
www.cs.hmc.edu/twiki/bin/view/CS5/TurtleDirections
for turtle installation and help
30Etch-a-Sketch ?
www.gvetchedintime.com
No way this is real but it is !
31Recursion vs Loops
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)
This seems like the place for a for!
32Finish rw to draw a "stock-market-type" random
walk of n steps. Use recursion
What does chai draw?
(1)
(2)
from random import def rw(n) """ move for
n uniform steps, randomly 45 deg.
left/up or right/down """ if n 0
return if choice('L','R') 'L'
'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 rw to draw a "stock-market-type" random
walk of n steps.
(2)
from random import def rw(n) """ move for
n uniform steps, randomly 45 deg.
left/up or right/down """ if n 0
return if choice('L','R') 'L'
'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 go back to the starting pose?
35hw3pr2 spiral
81
72.9
90
close-up of innermost part of the spiral
spiral( 100, 90, 0.9 )
100
spiral( initLength, angle, multiplier )
36hw3pr2 svTree
svTree( 100, 4 )
I wonder what happened to the leaves on that
tree ?
svTree( trunkLength, levels )
and more! (if you want)
37hw3pr2 your choice
more?
www.cs.hmc.edu/twiki/bin/view/CS5/TurtleDirections
38The Koch curve
snowflake( 100, 0 )
snowflake( 100, 1 )
snowflake( 100, 2 )
snowflake( 100, 3 )
snowflake( 100, 4 )
snowflake( 100, 5 )
39Homework 2
Functions
1
You may use loops or recursion - whichever you'd
like
Monty Hall
2
Is there a door 3?
40Monty Hall
Lets make a deal 63-86
Sept. 1990
inspiring the Monty Hall paradox
41Monty 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" ?
42Lab Homework 2 or 3
43Seeing 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!'
44Clearer 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
45the gift
LightPath, September 1999
46watching the charts
LightPath, six months later
47"brokerage" seems apt
LightPath, now
48T. T. Securities (TTS)
Input stock prices for a number of days in a
row, and then analyze that data .
49T. 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
50Functions
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 )
51Standard 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)
52T. 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
53T. 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
54The 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.
55Example
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
56Example
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
57What does this code print?
for x in range(3) for y in range(3) print
x, y
58Example
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
59Lab Questions
60Extra (!) 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!
???
???
61Monte Carlo p
Hw8 Pr3
A engineering challenge to estimate p using
everyday items...
62Easy as p
(1,1)
Visualize
(-1,-1)
63iPhone, geohot, and Von Neumann
George Hotz's iPhone
Before
After
In red one memory-access bit
soldered to be 1.8v (1)
64iPhone, 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.
65iPhone, geohot, and Von Neumann
George Hotz's iPhone
the trade
66Quiz
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?
67- 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 ?!
68Loopy 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 ?
69Loopy 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 ?
70Loopy 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 ?
71Loopy 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 ?
72Loopy 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 ?
73Planning 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'
74Planning 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
75Planning 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
76Challenge
Print the first N numbers in this series
Example
gtgtgt fib(11)
1 1 2 3 5 8 13 21 34 55 89
77Write 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
78input 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
79Why Assembly Language ?
Its only the foolish that never climb Mt. Fuji
-- or that climb it again.
Who writes most of the assembly language used?
80the 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
81Register r0 is always 0.
82Pure jumps not allowed!
Assembly language
Fortran, C, C, Basic,
GOTO
jump
83Who writes asembly?
I think the question is, "Who can spell assembly?"
people who need to talk to the processors
directly
84 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
85iPhone, geohot, and Von Neumann
George Hotz's iPhone
86iPhone, geohot, and Von Neumann
George Hotz's iPhone
Before
In red one memory-access bit
87iPhone, 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.
88iPhone, geohot, and Von Neumann
George Hotz's iPhone
Before
After
In red one memory-access bit
soldered to be 1.8v (1)
89iPhone, 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.
90iPhone, geohot, and Von Neumann
George Hotz's iPhone
the trade
91Thinking 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
92Thinking 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
93Thinking 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?!?