Lecture 9: Loops!

advertisement
IST338
Coding in
circles!
Thinking loopily
This week's
HmmmWork
#6 due Sunday!
and cumulatively
for a while
+=
sounds natural to me!
Today: Loops have arrived…
This week & next: putting loops to good use..
tutoring hours
through the
week(end)…
Putting the spring in spring break…
Putting the spring in spring break…
Don't misunderestimate DD!
Back to CS… !
Yenny Z. @ the Museum of Math…
Bailey Ahn with in-Motley-tutoring…
Where were we… ?
Alex C.
Eliot W.
Han J.
"The ultimate divider!"
Pure minterm Expansion…
"The ultimate divider!"
Pure minterm Expansion…
Brandon D. 2015
Faiz A.
Leanna N.
Wk 6: Assembly ~ why?
It's only the foolish who never climb
Mt. Fuji -- or who climb it again.
some tasks are better left to machines…
Recursive Hmmm
factorial, hw6pr4
00
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
read r1
setn r15 42
call r14 5
jump 21
nop
jnez r1 8
setn r13 1
jumpr r14
storer r1 r15
addn r15 1
storer r14 r15
addn r15 1
addn r1 -1
call r14 5
addn r15 -1
loadr r14 r15
addn r15 -1
loadr r1 r15
mul r13 r13 r1
jumpr r14
nop
write r13
halt
Hmmm
hw6
Looping Hmmm factorial,
similar to hw6pr2 and pr3
00
01
02
03
04
05
06
07
Functional
programming
read r1
setn r13 1
jeqz r1 6
mul r13 r13 r1
addn r1 -1
jumpn 02
write r13
halt
Iterative
programming
Hmmm… I think I'll
take Python!
Hmmm-thinking in Python
Loops in Python
def fac(x):
result = 1
while x != 0:
result *= x
x -= 1
return result
It figures a Python would prefer
looping to jumping!
Jumps in Hmmm
00
01
02
03
04
05
06
07
read r1
setn r13 1
jeqz r1 6
mul r13 r13 r1
addn r1 -1
jumpn 02
write r13
halt
Hmmm-thinking in Python
Loops in Python
def fac(x):
result = 1
while x != 0:
result *= x
x -= 1
return result
It figures a Python would prefer
looping to jumping!
Jumps in Hmmm
00
01
02
03
04
05
06
07
read r1
setn r13 1
jeqz r1 6
mul r13 r13 r1
addn r1 -1
jumpn 02
write r13
halt
Hmmm-thinking in Python
Loops in Python
def fac(x):
result = 1
while x != 0:
result *= x
x -= 1
return result
It figures a Python would prefer
looping to jumping!
Jumps in Hmmm
00
01
02
03
04
05
06
07
read r1
setn r13 1
jeqz r1 6
mul r13 r13 r1
addn r1 -1
jumpn 02
write r13
halt
Hmmm-thinking in Python
Loops in Python
def fac(x):
result = 1
while x != 0:
result *= x
x -= 1
return result
It figures a Python would prefer
looping to jumping!
Jumps in Hmmm
00
01
02
03
04
05
06
07
read r1
setn r13 1
jeqz r1 6
mul r13 r13 r1
addn r1 -1
jumpn 02
write r13
halt
Hmmm-thinking in Python
Loops in Python
def fac(x):
result = 1
while x != 0:
result *= x
x -= 1
return result
It figures a Python would prefer
looping to jumping!
Jumps in Hmmm
00
01
02
03
04
05
06
07
read r1
setn r13 1
jeqz r1 6
mul r13 r13 r1
addn r1 -1
jumpn 02
write r13
halt
Hmmm-thinking in Python
Loops in Python
def fac(x):
result = 1
while x != 0:
result *= x
x -= 1
return result
It figures a Python would prefer
looping to jumping!
Jumps in Hmmm
00
01
02
03
04
05
06
07
read r1
setn r13 1
jeqz r1 6
mul r13 r13 r1
addn r1 -1
jumpn 02
write r13
halt
Hmmm-thinking in Python
Loops in Python
def fac(x):
result = 1
while x != 0:
result *= x
x -= 1
return result
We get the
advantages of
explicit looping
AND self-contained
functions
All the advantages of
Hmmm? I'm sold!
Iterative design in Python
for
for x in [40,41,42]:
print x
jumpn, jeqzn, …
while
x = 42
while x > 0:
print x
x -= 1
the initial value is often not
the one we want in the end
variables vary
x = 41
x += 1
But we change it as we go…
addn r1 1
This slide is
four for for!
for loops
for x in [2,4,6,8]:
print x
for y in [7]*6:
print y
for c in 'down with loops!':
print c
for i in
print i
How could we get
this loop to run 42
times?
There are a range of answers to this one…
for!
This is the #1 for-loop error! (what? why?)
1
It's what the fox
says: Duck!
x is assigned each value
from this sequence
for x in [2,4,6,8]:
print 'x is', x
2
the BODY or BLOCK of the
for loop runs with that x
3
LOOP back to
step 1 for
EACH value
in the list
print 'Done!'
4
Code AFTER the loop will not
run until the loop is finished.
anatomy?
empty?
x unused?
That's why they're called variables
age = 41
The "old" value (41)
age = age + 1
The "new" value (42)
Truth-in-powerpoint disclosure: all of this is true, in base 11
Only in Python can one's
newer age be older than
one's older age… !
age += 1
That's why they're called variables
age = 41
Only in Python can one's
newer age be older than
one's older age… !
The "old" value (41)
age = age + 1
age += 1
The "new" value (42)
Python shortcuts
hwToGo = 7
hwToGo = hwToGo - 1
hwToGo
amoebas = 100000
amoebas = amoebas * 2
amoebas
u235 = 10000000000000;
u235 = u235 / 2
u235
four questions for for
for x in [1,2,3,4,5,6,7]:
print 'x is', x
avoid writing the whole list?
find the sum of the list?
showing partial sums?
factorial function?
fac with for
def fac( n ):
Hey! That's not
the right answer!
result = 1
for x in range(1,n+1):
result = result * x
return result
Warning: no one
else uses this term…
Laddering for loops
result
def fac( n ):
result = 1
for x in range(1,n+1):
result = result * x
return result
meets up with
Jacob's ladder
x
Quiz
What does the loop say?
R
Name(s): __________________________
x
x
result = 1
for x in [2,5,1,4]:
result *= x
print result
x = 0
for i in range(4):
x += 10
print x
L = ['golf','fore!','club','tee']
S = 'time to think this over! '
for i in range(len(L)):
result = ''
if i%2 == 1:
print L[i]
i%2
i
for i in range(len(S)):
if S[i-1] == ' ':
result += S[i]
print result
These answers seem unexpected, but still somehow familiar… !?
i
Quiz
What does the loop say?
result = 1
for x in [2,5,1,4]:
result *= x
print result
result
1
x
2
Quiz
What does the loop say?
x = 0
for i in range(4):
x += 10
print x
x
0
i
0
Quiz
What does the loop say?
L = ['golf','fore!','club','tee']
for i in range(len(L)):
if i%2 == 1:
print L[i]
L[i]
i%2
i
0
1
2
3
Quiz
What does the loop say?
result
S[i-1]
S[i]
i
' '
't'
'i'
'm'
'e'
' '
't'
'o'
' '
't'
'i'
'm'
'e'
' '
't'
'o'
' '
't'
0
1
2
3
4
5
6
7
8
S = 'time to think this over! '
result = ''
for i in range(len(S)):
if S[i-1] == ' ':
result += S[i]
print result
for: two types
L = [3, 15, 17, 7]
x
for x in L:
print x
element-based loops
for: two types
L[0]
L[1]
L[2]
L[3]
L = [3, 15, 17, 7]
0
1
2
3
i
for i in range(len(L))
print L[i]
for x in L:
print x
index-based loops
element-based loops
simpler vs. flexibler
L = [3, 15, 17, 7]
x
def sum(L):
total = 0
for x in L:
total += x
return total
element-based loops
simpler vs. flexibler
L = [3, 15, 17, 7]
0
1
2
3
i
def sum(L):
total = 0
for x in L:
total += x
return total
element-based loops
def sum(L):
total = 0
for i in range(len(L))
total += _____
return total
index-based loops
Perspective on for loops
At the top of a CS5 project file …
// Author:
// Purpose:
//
// Purpose:
//
Matt Beaumont
To get me out of CS5...
...no, really...
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
Perspective on for loops
Lisa Fowler @ IST380e…
At the top of a CS5 project file …
// Author:
// Purpose:
//
// Purpose:
//
Matt Beaumont
To get me out of CS5...
...no, really...
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
Perspective on for loops
Coworkers!
At the top of a CS5 project file …
// Author:
// Purpose:
//
// Purpose:
//
Matt Beaumont
To get me out of CS5...
...no, really...
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
Extreme Looping
What does this code do?
print 'It keeps on'
while True:
print 'going and'
print 'Phew! I\'m done!'
I'm whiling away the
time with this one!
Extreme Looping
Anatomy of a while
print 'It keeps on'
while
loop
the loop keeps on running as
long as this test is True
while True:
print 'going and'
print 'Phew! I\'m done!'
This won't print until the while loop finishes In this case, it never prints!
alternative tests?
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?
random.uniform!
screenshot
from '12
Pi day celebrators?
Hw8 Pr1
Pi from Pie?
p
Pizza is the universal
constant, after all…
(1,1)
Hw8 Pr1
Pie
Box
(-1,-1)
Estimating
π from pie?
(1,1)
Hw8 Pr1
Pie
Estimating
π from pie!
area
area
Box
(-1,-1)
4.0 *
π~
#
=
#
π
4
hits
hits
Try these…
What do these two loops return?
Let WORD = 'forty-two'
def count( WORD ):
n = 0
for c in WORD:
if c not in 'aeiou':
n += 1
return n
Let n = 12, then try n = 8
def mystery( n ):
while n != 1:
if n%2 == 0:
n = n/2
else:
return False
return True
12
8
Challenge: what are inputs for which mystery returns True?
L will be a non-empty
list of numbers.
def min( L ):
n will be a positive
integer >= 2
def isPrime( n ):
result = L[0]
for x in L:
if x
return result
[50,55,43,99,45,42]
An example list to consider…
index?
Hint: write a loop to check all possible divisors to see if they "work"…
Homework 8 preview
#1 ~ lab
The birthday paradox
#1 ~ Pi
Pi from Pie
#2
(Extra)
TTS Securities
ASCII Art
Remember the Hmmmwork 6 problems, too!
Loopy
thinking
Thinking in loops
for
while
x = 0
for x in range(42):
print x
while x < 42:
print x
x += 1
What are the design differences between
the two types of Python loops?
Loops: for or while?
whilePi(err)
err == how close to π we need to get
forPi(n)
n == number of darts to throw
indefinite # of
iterations
definite # of
iterations
Loops are
familiar ?!
Careful here!
Thanks: Melody S.
Loops are
familiar ?!
Homework 8 preview
#1 ~ lab
The birthday paradox
#1 ~ Pi
Pi from Pie
#2
(Extra)
TTS Securities
ASCII Art
Remember the Hmmmwork 6 problems, too!
Nested
Loops
Nested loops are familiar, too!
So close!
Nested loops
Life
clock
for y in range(84):
for m in range(12):
for d in range(f(m,y)):
for h in range(24):
for mn in range(60):
for s in range(60):
tick()
Nested loops!
for y in range(84):
for m in range(12):
for d in April
range(f(m,y)):
in
for h Claremont?
in range(24):
for mn in range(60):
for s in range(60):
tick()
s == 0
s == 59
mn == 0
Nested
loops' 2d
structure
One hour ~ 3600 seconds:
mn == 42
mn == 59
for mn in range(60):
for s in range(60):
tick()
Nested loops'
2d structure
for d in range(f(m)):
for m in range(1,13):
num_bdays(m,d)
how many shared
birthdays are in CS5?
vizwiz.blogspot.com/2012/05/how-common-is-your-birthday-find-out.html
Nested
loops via
ASCII Art
That's my type
of alien!
Creating 2d structure
col
0
row
0
1
2
1
2
3
# # # #
# # # #
# # # #
for row in range(3):
for col in range(4):
print "#"
This doesn't
work!
Creating 2d structure
[0,1,2]
for row in range(3):
[0,1,2,3]
for col in range(4):
print '#',
print
1
col
col
col
col
=
=
=
=
row =
col
0
row =
2
3
col
col
col
col
=
=
=
=
row
0
1
2
row =
col
col
col
col
=
=
=
=
Creating 2d structure
[0,1,2]
for row in range(3):
[0,1,2,3]
for col in range(4):
print '#',
print
1
col
col
col
col
=
=
=
=
row =
col
0
row =
2
3
col
col
col
col
=
=
=
=
row
0
1
2
row =
col
col
col
col
=
=
=
=
Creating 2d structure
for row in range(3):
for col in range(4):
if col == row:
print '#',
else:
print ' ',
print
col
0
row
0
1
2
1
2
3
0
col = 0
row =
col = 1
col = 2
col = 3
1
col = 0
row =
col = 1
col = 2
col = 3
row =
col
col
col
col
2
=
=
=
=
0
1
2
3
Match!
Name(s): _____________________
Birthday(s) ______________ !
+ what code creates
the fourth one?
[0,1,2]
for r in range(3):
for c in range(6):
[0,1,2,3,4,5]
if c > r:
print '#',
else:
print ' ',
print
for r in range(3):
for c in range(6):
if c%2 == 1:
print '#',
else:
print ' ',
print
for r in range(3):
for c in range(6):
if r%2 == c%2:
print '#',
else:
print ' ',
print
cols
0
1
2
3
4
0
# # # # #
# # # #
# # #
0
1
2
cols
5
0
2
rows
1
#
2
3
#
#
1
#
4
5
#
#
#
#
#
rows
cols
cols
0
0
1
2
rows
1
2
3
# # # #
# # #
# #
4
5
0
0
1
2
rows
Quiz
1
#
#
#
2
3
#
#
#
4
5
#
#
#
hw8pr2: T. T. Securities (TTS)
Analyze a list of data
day
0
day
1
day
2
day
3
day
4
a sequence of
stock prices, say
day
5
day
6
day
7
L = [ 40, 80, 10, 30, 27, 52, 5, 15 ]
The menu to implement:
(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:
User input
meters = raw_input('How many m? ')
cm = meters * 100
print 'That is', cm, 'cm.'
What will Python think?
I think I like these units better
than light years per year!
User input
meters = raw_input('How many m? ')
cm = meters * 100
print 'That is', cm, 'cm.'
What will Python think?
I think I like these units better
than light years per year!
Fix #1: convert to the right type
meters_str = raw_input('How many m? ')
meters = float( meters_str )
cm = meters * 100
print 'That is', cm, 'cm.'
'42'
name: meters_str
type: string
42.0
name: meters
type: float
4200.0
name: cm
type: float
Fix #2: use input
meters = input('How many m? ')
cm = meters * 100
print 'That is', cm, 'cm.'
input interprets its input
raw_input always returns a string
I always use input -- but
don't "quote" me on that.
A larger application…
def menu():
""" prints
print "(1)
print "(2)
print "(9)
our menu of options """
Input a new list of numbers"
I will divine the next element"
Quit"
def main():
""" handles user input for our menu """
while True:
menu()
Calls a helper
function
uc = input('Which option? ')
Perhaps uc the
reason for this?
def main():
""" handles user input for our menu """
L = [39,40,41] # a starting list
while True:
menu() # print menu
uc = input('Which option? ')
if uc == 9:
(9) Quit!
elif uc == 1:
(1) Get new list
elif uc == 2:
(2) other…
def main():
""" handles user input for our menu """
L = [39,40,41] # a starting list
while True:
menu() # print menu
uc = input('Which option? ')
if uc == 9:
break exits the loop
(9) Quit!
elif uc == 1:
(1) Get new list
use input to get a new L
elif uc == 2:
(2) other…
other functions, as needed
def main():
""" handles user input for our menu """
L = [39,40,41] # a starting list
while True:
menu() # print menu
uc = input('Which option? ')
if uc == 9:
break exits the loop
(9) Quit!
elif uc == 1:
(1) Get new list
use input to get a new L
elif uc == 2:
(2) other…
other functions, as needed
Functions you'll write
All use loops…
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:
def average( L )
def stdev( L )
2
(L[i]
L
)

av
i
len(L)
def minday( L )
def maxday( L )
webbrowser.open_new_tab(url)
XKCD's loop
and this was before there
were watches!
import webbrowser
url = "https://xkcd.com/1411/"
webbrowser.open_new_tab(url)
Min price
Just call min ?
What's the idea for finding the smallest (minimum) price?
day
0
day
1
day
2
day
3
day
4
day
5
day
6
day
7
L = [ 40, 80, 10, 30, 27, 52, 5, 15 ]
m=
m is the
"min so far"
track the value of the minimum so far as you loop over L
Min price
Just call min ?
What's the idea for finding the smallest (minimum) price?
day
0
day
1
day
2
day
3
day
4
day
5
day
6
day
7
L = [ 40, 80, 10, 30, 27, 52, 5, 15 ]
m=
m is the
"min so far"
track the value of the minimum so far as you loop over L
Min price vs. min day
day
0
day
1
day
2
day
3
day
4
day
5
day
6
day
7
L = [ 40, 80, 10, 30, 27, 52, 5, 15 ]
m=
40
m=
10
m=
5
5 is the
min price
def minprice( L ):
m = L[0]
for x in L:
if x < m:
m = x
return m
What about
the day of the
minimum
price?
Min price vs. min day
day
0
day
1
day
2
day
3
day
4
day
5
day
6
day
7
L = [ 40, 80, 10, 30, 27, 52, 5, 15 ]
m=
40
m=
10
m=
5
5 is the
min price
md =
md is the
"min day so far"
Min price vs. min day
day
0
day
1
day
2
day
3
day
4
day
5
day
6
day
7
L = [ 40, 80, 10, 30, 27, 52, 5, 15 ]
m is the
"min so far"
m=
40
m=
10
m=
5
5 is the
min price
md
=0
md is the
"min day so far"
md
=2
md
=6
6 is the
min day
day
0
day
1
day
2
day
3
day
4
day
5
day
6
day
7
L = [ 40, 80, 10, 30, 27, 52, 5, 15 ]
m is the
"min so far"
m=
40
m=
10
m=
5
5 is the
min price
md
=0
md
=2
md
=6
6 is the
min day
md is the
"min day so far"
def minday( L ):
m = L[0]
[0,1,2,3,4,5,6,7]
md = 0
for i in range(len(L)):
We loop through
if
the INDEX of
each element
return md
day
0
day
1
day
2
day
3
day
4
day
5
day
6
day
7
L = [ 40, 80, 10, 30, 27, 52, 5, 15 ]
m is the
"min so far"
m=
40
m=
10
m=
5
5 is the
min price
md
=0
md
=2
md is the
"min day so far"
def minday( L ):
m = L[0]
[0,1,2,3,4,5,6,7]
md = 0
for i in range(len(L)):
We loop through
if L[i] < m:
the INDEX of
m = L[i]
each element
md = i
return md
md
=6
6 is the
min day
personal motivation for TT securities…
LightPath, Summer 1999 ~ wedding gift…
LightPath, Summer 1999
LightPath, Spring 2000
Why it's called a brokerage
LightPath, Fall 2014
T. T. Securities
Software
side …
(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:
Hardware
side…
Investment analysis for the 21st century … and beyond!
T. T. Securities
Software
side …
(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:
Hardware
side…
Investment analysis for the 21st century … and beyond!
T. T. Securities
Back to
the future
Software
side …
(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:
Hardware
side…
Investment analysis for the 21st century … and beyond!
T. T. Securities
Back to
the future
Software
side …
(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:
Hardware
side…
Investment analysis for the 21st century … and beyond!
The TTS advantage!
Your stock's prices:
Day
0
1
2
3
4
5
6
7
Price
40.0
80.0
10.0
30.0
27.0
52.0
5.0
15.0
L = [ 40, 80, 10, 30, 27, 52, 5, 15 ]
What is the best
TTS investment
strategy here?
Important fine print:
To make our business plan realistic, however, we only allow selling after buying.
ASCII art...? How about ASCII video !
http://www.asciimation.co.nz/
Loops
def count(e,L):
counter = 0
for x in L:
if x == e:
counter += 1
return counter
count(5, [ 7, 5, 42, 5, 5 ])
Recursion
def count(e,L):
if L == []
return 0
elif L[0] == e:
return 1 + count(e,L[1:])
else:
return 0 + count(e,L[1:])
Loops
def count(e,L):
counter = 0
for x in L:
if x == e:
counter += 1
return counter
count(5, [ 7, 5, 42, 5, 5 ])
counter
x
e
5
count(5, [ 7, 5, 42, 5, 5 ])
Recursion
def count(e,L):
if L == []
return 0
elif L[0] == e:
return 1 + count(e,L[1:])
else:
return 0 + count(e,L[1:])
Write mindiff to return the smallest abs. diff.
between any two elements from L.
mindiff( [42,3,7,100,-9])
4
L
def mindiff( L ):
Hint: Use nested loops:
for y in L:
for x in L:
for y in range(4):
for x in range(4):
print abs(x-y),
Track the value of the
minimum so far as you
loop over L and R…
What does this
code print?
for y in range(4):
for x in range(4):
print abs(x-y),
print
x
y
0
1
2
3
0
1
2
3
0
1
2
3
1
0
1
2
2
1
0
1
3
2
1
0
The TTS advantage!
Your stock's prices:
L = [ 40, 80, 10, 30, 27, 52, 5, 15 ]
The TTS investment strategy:
Day
0
1
2
3
4
5
6
7
Price
40.0
80.0
10.0
30.0
27.0
52.0
5.0
15.0
to be realistic (for our VC backers), you must sell after you buy.
Homework 8 preview
Remember Hmmmwork 6 problems, too!
#1 ~ lab
The birthday paradox
#1 ~ Pi
Pi from Pie
#2
(Extra)
TTS Securities
ASCII Art
Loopy
thinking
Loops
Recursion
def fac( N ):
result = 1
for x in range(1,N+1):
result *= x
return result
def fac( N ):
if N == 1:
return 1
else:
return N*fac(N-1)
L
minday
return the index
of L's minimum.
How do we loop
through the INDEX of
each element?
How do we ensure
m keeps track of
the minimum?
How and where should
we update mndy?
>>> minday( [9, 8, 5, 7, 42] )
2
0
1
2
3
4
index
def minday( L ):
m = L[0]
mndy = 0
for
if
:
< m:
m =
return mndy
index-based loop
Write diff to return the smallest
abs. diff. between any value
from L and any value from R.
Only consider absolute differences.
L and R will be lists of numbers.
def diff( L, R ):
L
R
>>> diff( [42,3,7] , [6,0,-5] )
1
Hint: Adapt the nested loops below!
for x in range(3):
for y in range(3):
print x, y
Aha! Track the value of the minimum so far as you loop over L and R…
Seems more like twothirds term to me...
CS 5 Today
infinitely nested structure…
CS Midterm
Thursday, Nov. 6
In-class, written
Page of notes is OK
Topics
• Recursion in Python
from finitely nested loops
Homework 8
Loops! due 11/3
• Function composition
• Circuit design
• Hmmm assembly code
• Loops in Python
See online practice…
Python and images
from cs5png import *
inputs are width and height
image = PNGImage( 300, 200 )
image.plotPixel( 10, 100 )
image.plotPixel( 42, 42, (255,0,0) )
image.saveFile( )
These functions are clearly
plotting something – if only I
knew what they were up to...
Python and images
from cs5png import *
inputs are width and height
image = PNGImage( 300, 200 )
objects are variables that can contain their
own functions, often called methods
image.plotPixel( 10, 100 )
image.plotPixel( 42, 42, (0,0,255) )
image.saveFile( )
These functions are clearly
plotting something – if only I
knew what they were up to...
from cs5png import *
def testImage():
""" image demonstration """
WD = 200
HT = 200
image = PNGImage( WD, HT )
Imagining
Images
thicker line?
other diagonal?
for row in range(HT):
for col in range(WD):
stripes ?
thicker stripes?
thatching?
if col == row:
image.plotPoint( col, row )
image.saveFile()
Quiz
Try this on the back page first…
[0,1,2]
for r in range(3):
for c in range(6):
[0,1,2,3,4,5]
if c > r:
print '#',
else:
print ' ',
print
for r in range(3):
for c in range(6):
if c%2 == 1:
print '#',
else:
print ' ',
print
for r in range(3):
for c in range(6):
if r%2 == c%2:
print '#',
else:
print ' ',
print
cols
0
1
2
3
4
0
# # # # #
# # # #
# # #
0
1
2
cols
5
0
#
rows
2
3
#
#
1
2
1
#
4
5
#
#
#
#
#
rows
cols
cols
0
0
1
2
rows
1
2
3
# # # #
# # #
# #
4
5
0
0
1
2
rows
1
#
#
#
2
3
#
#
#
4
5
#
#
#
L
return the index
of L's minimum.
We loop through the
INDEX of each element
How do we ensure
minval tracks the
minimum?
How and where should
we update minday?
>>> minday( [9, 8, 5, 7, 42] )
2
0
1
2
3
4
index
def minday( L ):
minval = L[0]
minday = 0
IND = range(len(L))
for i in IND:
if
< minval:
return minday
index-based loop
(1) Finish this code to return the
index (day) of L's minimum.
L
>>> minday( [9, 8, 5, 7, 42] )
2
0
1
2
3
4
Try it!
(2) What does this code print?
index
def minday( L ):
minval = L[0]
minday = 0 # minday!
IND = range(len(L))
Try an indexfor i in IND: based loop!
if
< minval:
for y in range(4):
for x in range(4):
print abs(x-y),
print
(3) Write minabsdiff to return the smallest
abs. diff. between any two elements from L.
L
>>> minabsdiff( [42,1,7,100,-9])
6
Only consider absolute differences.
L will be a list of numbers.
Hint: Use nested loops!
return minday
def mindiff( L ):
Hint: keep track of the min m AND
the day of the min mndy
Extra: How could we save more
than half of this computation!?
L
minday
return the index
of L's minimum.
We loop through the
INDEX of each element
How do we ensure
minval tracks the
minimum?
How and where should
we update minday?
>>> minday( [9, 8, 5, 7, 42] )
2
0
1
2
3
4
index
def minday( L ):
minval = L[0]
minday = 0
IND = range(len(L))
for i in IND:
if
< minval:
return minday
index-based loop
L
minday
return the index
of L's minimum.
def minday( L ):
mnvl = L[0]
mndy = 0
day = 0
for x in L:
if x < mnvl:
mnvl = x
mndy = day
day += 1
return mndy
element-based loop
>>> minday( [9, 8, 5, 7, 42] )
2
0
1
2
3
4
Create a "counter"
that will keep track of
the current day.
IF we find a smaller
min, save which day
it was in mndy
Regardless, we add 1 to day so
that we're keeping track!
index
What does this
code print?
for y in range(4):
for x in range(4):
print abs(x-y),
print
x
y
0
1
2
3
0
1
2
3
0
1
2
3
1
0
1
2
2
1
0
1
3
2
1
0
minabsdiff( [42,1,7,100,-9])
6
L = [42, 1, 7, 100, -9]
0
0 0
0
0
def mindiff( L ):
for i in range(len(L)):
for j in range(len(L)):
Write mindiff to return the smallest abs. diff.
between any two elements from L.
Track the value of the
minimum so far as you
loop over L twice…
Write mindiff to return the smallest abs. diff.
between any two elements from L.
mindiff( [42,3,7,100,-9])
4
L
def mindiff( L ):
Hint: Use nested loops:
for y in L:
for x in L:
for y in range(4):
for x in range(4):
print abs(x-y),
Track the value of the
minimum so far as you
loop over L and R…
What
does
this
print?
for row in range(side): [0,1,2,3,4]
for col in range(side): [0,1,2,3,4]
if row >= col:
print '+',
else:
print ' ',
print
for row in range(side):
for col in range(side):
if
print '%',
else:
print ' ',
print
What if
tests
print
these? for row in range(side):
for col in range(side):
if
print 'C',
else:
print ' ',
print
columns
0
1
2
3
4
0
1
2
3
4
0
1
rows
Nested loops: Rows vs. columns
For these loops, let side=5:
2
3
4
0
1
2
3
4
0
1
2
3
4
%
%
%
%
%
% % % %
% % %
% %
%
0
1
2
C
C
C
C
C
C
C
C
C
C
C
C
C
C
C
3
4
C C
C
C
C C
columns
for row in range(5):
for col in range(5):
if
print '%',
else:
print ' ',
print
for row in range(5):
for col in range(5):
if
print 'C',
else:
print ' ',
print
0
1
rows
for row in range(5):
for col in range(5):
if row >= col:
print '+',
else:
print '-',
print
0
A
B
2
3
4
0
1
2
3
4
0
1
2
3
4
1
2
3
4
3
4
+
+
+
+
+
+
+
+
+
+
+
+
0
1
2
%
%
%
%
%
+
+
+
% % % %
% % %
% %
%
0
1
2
3
4
C
C
C
C
C
C
C
C
C
C
C
C
C
C
C
C C
C
C
C C
columns
for row in range(side):
for col in range(side):
if
print row,
else:
print ' ',
print
for row in range(side):
for col in range(side):
if
print row,
else:
print ' ',
print
0
0
1
2
3
4
0
1
rows
for row in range(side):
for col in range(side):
if row >= col:
print row,
else:
print ' ',
print
A
C
2
3
4
0
0
1
2
3
4
0
1
2
3
4
0
1
2
3
4
1
2
3
4
B
0 0 0 0 0
1 1 1
2
3 3 3
4 4 4 4 4
1
2 2
3 3 3
4 4 4 4
1
2
3
4
0 0 0 0
1 1 1
2 2
3
D
0
1
2
0
1
2
3
4
0
1
2
3
4
0
1
2
3
4
3
4
0 0
1
3
4 4
Extra! how about
this hourglass?
Lab 8: the Mandelbrot Set
Consider an update rule
for all complex numbers c
z0 = 0
zn+1 = zn2 + c
Python's complex #s
Nothing's too
complex for
Python!
>>>
c = 3 + 4j
>>>
3.0
c.real
>>>
4.0
c.imag
>>>
5.0
abs(c)
Mandelbrot Definition
z0 = 0
Consider an update rule
for all complex numbers c
zn+1 = zn2 + c
Small values of c keep
the sequence near the
origin, 0+0j.
z3
c
z1
z0
z2
z4
z5
some "stick around":
oscillate or converge
Imaginary axis
Real axis
Mandelbrot Definition
z0 = 0
Consider an update rule
for all complex numbers c
Small values of c keep
the sequence near the
origin, 0+0j.
zn+1 = zn2 + c
c
Benoit B.
Mandelbrot
1924 – 2010
Real axis
c
Imaginary axis
Other values of c
make the sequence
head to infinity.
Lab 8: the Mandelbrot Set
Consider an update rule
for all complex numbers c
z0 = 0
zn+1 = zn2 + c
Lab 8: the Mandelbrot Set
Consider an update rule
for all complex numbers c
z0 = 0
zn+1 = zn2 + c
Mandelbrot Set ~ points that stick around
The shaded area are points that do not diverge for z = z**2 + c
Higher-resolution M. Set
-2 + 1j
connected
1 + 1j
finite area
 perimeter!
-2 - 1j
1 - 1j
The black pixels are points that do not diverge for z = z**2 + c
Chaos?
Complex things always consisted of simple parts…
Before the M. Set, complex things
were made of simple parts:
Chaos!
This was a "naturally occurring" object where
zooming uncovers more detail, not less:
not self-similar but quasi-self-similar
http://www.youtube.com/watch?v=0jGaio87u3A
The black pixels are points that do not diverge for z = z**2 + c
What are these colors?
The black pixels are points that do not diverge for z = z**2 + c
What are these colors?
escape
velocities
Atlas of the M. Set
In the Seahorse Valley….
Happy Mandelbrotting!
www.cs.hmc.edu/~jgrasel/projects
http://www.youtube.com/watch?v=0jGaio87u3A
Hw8 Pr2
A engineering challenge:
estimate p using everyday items...
(1,1)
Pie
(-1,-1)
Box
Creating 2d structure
[0,1,2]
for row in range(3):
[0,1,2,3]
for col in range(4):
print '#',
print
1
col
col
col
col
=
=
=
=
row =
col
0
row =
2
3
col
col
col
col
=
=
=
=
row
0
1
2
row =
col
col
col
col
=
=
=
=
Tracking rows and columns
for row in range(3):
row =
for col in range(4):
print '$',
print
0
col
col
col
col
=
=
=
=
row =
1
2
3
col
col
col
col
col
=
=
=
=
0
1
2
row
row =
col
col
col
col
=
=
=
=
Name(s): ______________________________
for row in range( 3 ):
for col in range( 6 ):
print ______,
print
cols
0
0
1
2
1
2
3
4
5
0 1 2 3 4 5
0 1 2 3 4 5
0 1 2 3 4 5
rows
Change each block of code so that it will print the examples below:
for row in range( 3 ):
for col in range( 6 ):
print ____________,
print
0 0 0 0 0 0
1 1 1 1 1 1
2 2 2 2 2 2
for row in range( 3 ):
for col in range( 6 ):
print ____________,
print
0 1 2 3 4 5
1 2 3 4 5 6
2 3 4 5 6 7
for row in range( 3 ):
for col in range( 6 ):
print ____________,
print
0 1 0 1 0 1
1 0 1 0 1 0
0 1 0 1 0 1
Name(s): ______________________________
columns
What
does
this
print?
for row in range(side):
for col in range(side):
if row >= col:
print row,
else:
print ' ',
print
for row in range(side):
for col in range(side):
if
What if
tests
print
these
two?
print row,
else:
print ' ',
print
for row in range(side):
for col in range(side):
if
print row,
else:
print ' ',
print
0
1
2
3
4
0
1
rows
Nested loops: Rows vs. columns
For these loops, let side=5:
2
3
4
0
1
2
3
4
0 0 0 0
1 1 1
2 2
3
0
1
2
3
4
0
1
2
3
4
0
1
2
3
4
0 0
1
3
4 4
Extra! how
about the
hourglass?
0 0 0 0 0
1 1 1
2
3 3 3
4 4 4 4 4
Name(s): ______________________________
columns
What
does
this
print?
for row in range(side):
for col in range(side):
if row >= col:
print row,
else:
print ' ',
print
for row in range(side):
for col in range(side):
if
What if
tests
print
these
two?
print row,
else:
print ' ',
print
for row in range(side):
for col in range(side):
if
print row,
else:
print ' ',
print
0
1
2
3
4
0
1
rows
Nested loops: Rows vs. columns
For these loops, let side=5:
2
3
4
0
1
2
3
4
0 0 0 0
1 1 1
2 2
3
0
1
2
3
4
0
1
2
3
4
0
1
2
3
4
0 0
1
3
4 4
Extra! how
about the
hourglass?
0 0 0 0 0
1 1 1
2
3 3 3
4 4 4 4 4
fractal CAT ?
infinitely nested structure…
CS Midterm
Thursday Nov. 3
Seems more like twothirds term to me...
In-class, written
Page of notes is OK
from finite nested loops
Homework 8: due eve. of 10/31
LAC hrs: Friday, 2-4pm
Topics
• Recursion in Python
• Software design
• Circuit design
• Hmmm assembly code
• Loops in Python
www.cs.hmc.edu/~jgrasel/mandelbrot
fractal NYAN cat!
Hw8 Pr2
A engineering challenge:
estimate p using everyday items...
(1,1)
Pie
(-1,-1)
Hw8 Pr2
A engineering challenge:
estimate p using everyday items...
(1,1)
Pie
(-1,-1)
Box
Loops: for or while?
pi_one(e)
e == how close to π
we need to get
pi_two(n)
n == number of
darts to throw
Which function will use which kind of loop?
Tracking rows and columns
for row in range(3):
for col in range(4):
print '$',
print
0
0
1
2
rows
1
2
3
cols
for row in range( 3 ):
for col in range( 6 ):
print ______,
print
cols
0
0
1
2
1
2
3
4
5
0 1 2 3 4 5
0 1 2 3 4 5
0 1 2 3 4 5
rows
Change each block of code so that it will print the examples below:
for row in range( 3 ):
for col in range( 6 ):
print ____________,
print
0 0 0 0 0 0
1 1 1 1 1 1
2 2 2 2 2 2
for row in range( 3 ):
for col in range( 6 ):
print ____________,
print
0 1 2 3 4 5
1 2 3 4 5 6
2 3 4 5 6 7
for row in range( 3 ):
for col in range( 6 ):
print ____________,
print
0 1 0 1 0 1
1 0 1 0 1 0
0 1 0 1 0 1
Name(s): ______________________________
columns
What
does
this
print?
for row in range(side):
for col in range(side):
if row >= col:
print row,
else:
print ' ',
print
for row in range(side):
for col in range(side):
if
What if
tests
print
these
two?
print row,
else:
print ' ',
print
for row in range(side):
for col in range(side):
if
print row,
else:
print ' ',
print
0
1
2
3
4
0
1
rows
Nested loops: Rows vs. columns
For these loops, let side=5:
2
3
4
0
1
2
3
4
0 0 0 0
1 1 1
2 2
3
0
1
2
3
4
0
1
2
3
4
0
1
2
3
4
0 0
1
3
4 4
Extra! how
about the
hourglass?
0 0 0 0 0
1 1 1
2
3 3 3
4 4 4 4 4
Feedback ... on feedback!
Images and 2d loops
How could you change this
code (the if test) to produce
this triangle image?
def test():
""" demonstrating images """
width = 200
height = 200
image = PNGImage( width, height )
for col in range(width):
for row in range(height):
What 2d loops would
create a checkerboard
image, pixel-by-pixel?
def test():
""" demonstrating images """
width = 8
height = 6
image = PNGImage( width, height )
for col in range(width):
for row in range(height):
if col == row:
image.plotPoint( col, row )
image.saveFile(
)
image.saveFile( )
How could you change this code so that
it produces an triangle like this?
def triangle():
""" demonstrating images """
width = 200
height = 200
image = PNGImage( width, height )
# a 2d loop over each pixel
for col in range(width):
for row in range(height):
if
image.plotPoint( col, row )
What 2d loops would create a checkerboard image?
def checkerboard():
… usual image stuff here …
# loop over each pixel
for col in range(width):
for row in range(height):
image.plotPoint( col, row )
Loops: for or while?
pi_one(e)
e == how close to π
we need to get
pi_two(n)
n == number of
darts to throw
Which function will use which kind of loop?
Images and 2d loops
How could you change this
code (the if test) to produce
this triangle image?
def test():
""" demonstrating images """
width = 200
height = 200
image = PNGImage( width, height )
for col in range(width):
for row in range(height):
What 2d loops would
create a checkerboard
image, pixel-by-pixel?
def test():
""" demonstrating images """
width = 8
height = 6
image = PNGImage( width, height )
for col in range(width):
for row in range(height):
if col == row:
image.plotPoint( col, row )
image.saveFile(
)
image.saveFile( )
Mandelbrot Set: issues
Consider the following update rule for
all complex numbers c:
z0 = 0
zn+1 = zn2 + c
What concerns might arise
in generating this image?
The shaded area are
points that do not diverge.
Pixels vs. "real" values
1.0
-2.0
1.0
-1.0
Drawing happens in pixel-coords. Mandelbrot testing happens in real coords.
Nature > Imagination?
Lab 9: the Mandelbrot Set
Consider the following update rule for
all complex numbers c:
z0 = 0
zn+1 = zn2 + c
Benoit M.
If c does not diverge, it's in the M. Set.
Imaginary axis
z3
c
z1
z0
z2
z4
Real axis
Lab 9: the Mandelbrot Set
Consider the following update rule for
all complex numbers c:
z0 = 0
zn+1 = zn2 + c
Benoit M.
If c does not diverge, it's in the M. Set.
Imaginary axis
z3
c
z1
z0
z2
z4
Real axis
example of a non-diverging cycle
Lab 9: the Mandelbrot Set
Consider the following update rule for
all complex numbers c:
z0 = 0
zn+1 = zn2 + c
The shaded area are points that do not diverge.
Python and images
import bmp.py
for creating and saving images
Eco-friendly
bitmps !
image = BitMap( 300, 200, Color.GREEN )
creates a bitmap object
and names it image
Python and images
import bmp.py
for creating and saving images
Eco-friendly
bitmps !
image = BitMap( 300, 200, Color.GREEN )
creates a bitmap object
and names it image
objects are software abstractions
containing structured information
Python and images and objects
import bmp.py
image = BitMap( 300, 200, Color.GREEN )
here, a bitmap object named image
is calling an internal method named saveFile
image.saveFile( "test.bmp" )
objects are variables that can contain
their own functions, often called methods
Python and images and objects
import bmp.py
image = BitMap( 300, 200, Color.GREEN )
image.setPenColor( Color.Red )
image.plotPixel( 150, 100 )
two more
internal
methods
image.saveFile( "test.bmp" )
objects are variables that can contain
their own functions, often called methods
Mandelbrot Set: properties
The set is connected.
The set's boundary is a fractal of dimension 2 (!)
"infinite detail"
The points nearer the set escape to  more slowly.
can color points based on
how quickly they escape…
not 100% self-similar but quasi-self-similar:
http://www.youtube.com/watch?v=gEw8xpb1aRA
Jonathan Coulton wrote a song about it
Mandelbrot Set: song
chorus
chorus…
Jonathan Coulton wrote a song about it
Hw8 Pr2
Pi from Pie?
Executives from CBS* have stranded
several teams of CS5ers on a sandy
desert island with only Dominos'
delivery #, and $7.99. The teams then
compete to see who can estimate pi
more accurately before being
consumed by carnivorous slugs…
*The Claremont Broadcasting Station
* Note: $7.99 is not enough to get you the meat-lovers pizza,
which would distract the carnivorous slugs… .
An image alternative…
http://www.asciimation.co.nz/
ASCII Images
Print 4 rows
for i in range(4):
print “#”*8
print automatically
adds a newline
Creates line to print
########
########
########
########
Output
Who are you calling simple?
ASCII Images
Print 4 rows
for i in range(4):
print “#”*8
print automatically
adds a newline
Creates line to print
########
########
########
########
Output
Who are you calling simple?
For this problem,
string multiplication
is not allowed.
Without string multiplication…
Print 4 rows
for i in range(4):
for j in range(8):
print “#”
print 8 chars on each line
?
Output ?
Any problems???
Without string multiplication…
for i in range(4):
for j in range(8):
print “#”,
Comma suppresses newline
Output ?
Now OK???
Try it!
What code would print this “ASCII quilt”
with height rows and width columns ?
cols 0
rows
for row in range(height):
for col in range(width):
0
1
2
3
4
5
#
*
#
*
#
*
1
2
3
4
5
6
7
8
#
*
#
*
#
*
*
#
*
#
*
#
#
*
#
*
#
*
#
*
#
*
#
*
*
#
*
#
*
#
#
*
#
*
#
*
#
*
#
*
#
*
*
#
*
#
*
#
Without string multiplication…
for i in range(4):
for j in range(8):
print “#”,
print
comma adds spaces
just prints a newline
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
Output
Close enough!
Without extra spaces…
import sys
for i in range(4):
for j in range(8):
sys.stdout.write('#')
print
method (function) that
prints only its input
software object representing the
screen's standard output
########
########
########
########
Output
Try it!
What code would print this “ASCII flag” ?
-- first, with 6 rows and 9 columns, then
with height rows and width columns.
#
*
#
*
#
*
*
*
*
*
*
*
*
*
*
*
*
*
#
*
#
*
#
*
*
*
*
*
*
*
*
*
*
*
*
*
#
*
#
*
#
*
*
*
*
*
*
*
*
*
*
*
*
*
Objects, objects, everywhere!
>>> L = []
# create a list, L
>>> dir(L)
# see all of L's methods
all list methods appear -- lots of them including
append, index, remove, and sort
>>> help(L.sort)
>>> help(L.index)
# I wonder…
# What does this do?
integers?
operators?
Another mini method
def mini( L ):
""" returns the DAY of the
lowest-priced stock """
I guess you really can't
beat the stock index !
use L.index
integers?
operators?
strings?
An image alternative…
http://www.asciimation.co.nz/
ASCII Images
Print 4 rows
for i in range(4):
print “#”*8
print automatically
adds a newline
Creates line to print
########
########
########
########
Output
Who are you calling simple?
ASCII Images
Print 4 rows
for i in range(4):
print “#”*8
print automatically
adds a newline
Creates line to print
########
########
########
########
Output
Who are you calling simple?
For this problem,
string multiplication
is not allowed.
Without string multiplication…
Print 4 rows
for i in range(4):
for j in range(8):
print “#”
print 8 chars on each line
?
Output ?
Any problems???
Without string multiplication…
for i in range(4):
for j in range(8):
print “#”,
Comma suppresses newline
Output ?
Now OK???
Try it!
What code would print this “ASCII quilt”
with height rows and width columns ?
cols 0
rows
for row in range(height):
for col in range(width):
0
1
2
3
4
5
#
*
#
*
#
*
1
2
3
4
5
6
7
8
#
*
#
*
#
*
*
#
*
#
*
#
#
*
#
*
#
*
#
*
#
*
#
*
*
#
*
#
*
#
#
*
#
*
#
*
#
*
#
*
#
*
*
#
*
#
*
#
Without string multiplication…
for i in range(4):
for j in range(8):
print “#”,
print
comma adds spaces
just prints a newline
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
Output
Close enough!
Without extra spaces…
import sys
for i in range(4):
for j in range(8):
sys.stdout.write('#')
print
method (function) that
prints only its input
software object representing the
screen's standard output
########
########
########
########
Output
Try it!
What code would print this “ASCII flag” ?
-- first, with 6 rows and 9 columns, then
with height rows and width columns.
#
*
#
*
#
*
*
*
*
*
*
*
*
*
*
*
*
*
#
*
#
*
#
*
*
*
*
*
*
*
*
*
*
*
*
*
#
*
#
*
#
*
*
*
*
*
*
*
*
*
*
*
*
*
Design - not just software
Please see instructions on HW 9. You have some
choice on what parts of this chapter to read.
Design guidelines
No magic numbers!
Keep constants together at
top with meaningful names…
def test():
""" demonstrating images """
width = 200
height = 200
image = BitMap( width, height )
What! No magic??
# a 2d loop over each pixel
for col in range(width):
for row in range(height):
if col == row:
image.plotPoint( col, row )
image.saveFile( "test.bmp" )
self-documenting design
Design guidelines
Anticipate change
def test(
""" demonstrating images """
width = 200
height = 200
image = BitMap( width, height )
# a 2d loop over each pixel
for col in range(width):
for row in range(height):
if col == row:
image.plotPoint( col, row )
image.saveFile( "test.bmp" )
• swapping arguments and
hand-set values
• default arguments
Design guidelines
Modularity: composing small pieces
Design guidelines
Modularity: composing small pieces
functions!
See you in lab!
Design
An iterative image
import bmp.py
“Quiz” Part$ 1
# &
Write the code to print this
piece of “ASCII art” (with or
without the spaces)
#
& # & #
& # & #
& # & #
&
&
&
&
#
#
#
#
&
&
&
&
#
#
#
#
An iterative image
import bmp.py
Fix #1: use a type converter
meters = float(raw_input('How many m? '))
cm = meters * 100
print 'That is', cm, 'cm.'
1.0
name: meters
type: float
100.0
name: cm
type: float
check out my newly installed
float converter!
The type of variable
(box) matters!
Fix #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.
Fix #2: use input()
# gets processed input from user
meters = input('How many m? ')
I always use input -- but
don't quote me on that.
cm = meters * 100
print 'That is', cm, 'cm.'
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
Procrastination Programming
Every while loop can be a
while True: loop!
- just be sure to break!
Give me a break !
import random
escape = 0
I'll figure out later how
to get out of this loop!
while True:
print 'Help! Let me out!'
escape = random.choice([41,42,43])
if escape == 42:
OK – I'll stop the loop
break
now and continue with
the code after the loop
print 'At last!'
compare return
Seeing into the future…
def menu():
""" prints
print "(1)
print "(2)
print "(9)
our menu of options """
Input a list of numbers"
Guess the next element"
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!'
def seer():
""" handles user input for our menu """
Clearer
Vision
while True:
menu()
uc = input('Which option? ')
print 'The inner eye does not see upon command!'
if uc ==
the gift…
LightPath, September 1999
watching the charts…
LightPath, six months later…
"brokerage" seems apt…
LightPath, now…
T. T. Securities (TTS)
Input stock prices for a number of days in a row,
and then analyze that data… .
T. 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
Functions
There are a number of formulas, but we will use this one:
functions
def average( L )
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:
def stdev( L )
def mini( L )
def maxi( L )
Standard Deviation
There are a number of formulas, but we will use this one:
functions
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:
def stdev( L ):

i
(L[i] - Lav)2
len(L)
T. 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
T. 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
The TTS advantage!
Your stock's prices:
L = [ 40, 80, 10, 30, 27, 52, 5, 15 ]
The TTS investment strategy:
Day
0
1
2
3
4
5
6
7
Price
40.0
80.0
10.0
30.0
27.0
52.0
5.0
15.0
but, you must sell after you buy.
Alter this code to return the
index of L's minimum.
"Quiz"
Example:
>>> mini( [9,8,1,7] )
2
Return the min difference
between one value from X
and one value from Y.
Example:
What does this code print?
>>> diff( [7,3],[0,6] )
1
Only consider unsigned differences.
consider "accumulating" the minimum index
in addition to the minimum value.
def mini( L ):
min = L[0]
for x in L:
if x < min:
min = x
return
You may want to change the loop!
for x in range(3):
for y in range(3):
print x, y
X and Y will be lists of numbers
Hint: adapt this code
def diff( X, Y ):
Alter this code to return the
index of L's minimum.
def mini( L ):
min = L[0]
Example:
>>> mini( [9,8,1,7] )
2
def mini( L ):
min = L[0]
for x in L:
if x < min:
min = x
for
:
if
< min:
min =
return
return
SAME LOOP
INDEX-BASED LOOP
returning both??
What does this code print?
for x in range(3):
for y in range(3):
print x, y
for x in range(3):
for y in range(3):
print x, y
Example:
Hint: adapt this code
>>> diff( [7,3],[0,6] )
1
Return the minimum difference between one value from X and one value from Y.
def diff( X, Y ):
Only consider unsigned differences.
X and Y will be lists of numbers
Hw8 Pr3
Monte Carlo p
A engineering challenge: to estimate p using everyday items...
Easy as p
(1,1)
Visualize:
(-1,-1)
to inf. and
beyond!
2d, 3d Loops
More efficient, but also more to keep track
of with each additional dimension
definite
iteration
while
indefinite
iteration
Extra (!) funky series
Diverges!
• 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 9’s…
1/1 + 1/2 + … + 1/8 + 1/9 + … +1/18 + 1/19
+ … + 1/88 + 1/89 + 1/90 + 1/91 + …
Have a great weekend!
iPhone, geohot, and Von Neumann
George Hotz's iPhone
Before
After
In red: one memory-access bit
soldered to be +1.8v (1)
iPhone, 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
The 4 32-bit memory
locations it checks are
0xA0000030
0xA000A5A0
0xA0015C58
0xA0017370
10100000000000000000000000110000
10100000000000001010010110100000
10100000000000010101110001011000
10100000000000010111001101110000
1
George Hotz's iPhone
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.
The memory locations it
actually checks are thus
10100000000001000000000000110000
10100000000001001010010110100000
10100000000001010101110001011000
10100000000001010111001101110000
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 AT&T.
iPhone, geohot, and Von Neumann
George Hotz's iPhone
the trade
“Quiz”
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?
• 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 ?!
Loopy 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 ?
Loopy 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 s[i] == '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 ?
Loopy 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 s[i] == 'a' or s[i] == '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 ?
Loopy 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 s[i] == 'a' and s[i-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 ?
Loopy 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 ?
Planning 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'
Planning 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…
Planning 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
Loop through the string:
for i in range(0,len(s)):
if we do see an 'a'
if s[i] == 'a':
if the PREVIOUS letter is NOT an 'a'
if s[i-1] != 'a':
Start a Run!
cur = 1
if the PREVIOUS letter IS an 'a'
else:
Continue our run!
cur = cur + 1
if cur > MAX:
Check for a new maximum…
MAX = cur
Keep track of CurRun, MaxRun
print 'Max is', MAX
Challenge
Example:
>>> fib(11)
1 1 2 3 5
Print the first N numbers
in this series…
8
13
21
34
55
89
Illustration of
scale( pix, pixMax, floatMin, floatMax )
Image
pixel
column
range
real
range
0
floatMin
pix
pixMax
output of
scale
floatMax
input 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
reply = input('Enter
interprets what the
user types as a
string of characters
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
ASCII Art
Print 3 rows
for row in range(3):
print automatically
print '#'*4
adds a newline
Creates line to print
####
####
####
Output
A closer look…
for row in range(3):
print '$'*4
$$$$
$$$$
$$$$
Output
No string * !
for row in range(3):
print '$'*4
$$$$
$$$$
$$$$
For these problems,
string multiplication
is not allowed.
Output
What else could be done?
Without string multiplication…
Print 3 rows
for row in range(3):
for col in range(4):
print '$'
nested loops!
print 4 chars on each line
(columns)
Output ?
Without string multiplication…
Print 3 rows
for row in range(3):
for col in range(4):
print '$',
nested loops!
print 4 chars on each line
(columns)
Comma suppresses newline
Output ?
Without string multiplication…
Print 3 rows
for row in range(3):
for col in range(4):
nested loops!
print '$',
print
print 4 chars on each line
(columns)
$ $ $ $
$ $ $ $
$ $ $ $
Comma suppresses newline
plain print produces newline
tracking cols and rows!
Variations!
def rectangle( width, height ):
""" prints a rectangle of $ """
for row in range(
for col in range(
print '$',
print
):
):
Beyond boxes…
cols 0
rows
0
What code will print this
triangle with H rows… ?
1
2
3
4
def tri( H ):
5
0
0
0
0
0
0
1
1
1
1
1
1
for row in range(H):
for col in range(
print col,
print
):
2
3
4
5
2
2 3
2 3 4
2 3 4 5
Python and images: Natural nesting!
from cs5png import *
image = PNGImage( 30, 20 )
creates an image object
and names it image
inputs are width and height
Python and images: Natural nesting!
from cs5png import *
image = PNGImage( 30, 20 )
creates an image object
and names it image
inputs are width and height
objects are software abstractions
containing structured information
I guess these
images are
objectionable!
Download