is 313 : putting loops to work for you
DESCRIPTION
IS 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, ? ]. - PowerPoint PPT PresentationTRANSCRIPT
IS 313: Putting loops to work for youW
hat'
s next?
[ 1, 11, 21, 1211, 111221, ? ]
[ -35, -24, -13, -2, 9, 20, 31, ? ]
[ 2, 22, 222, ? ]
[ 26250, 5250, 1050, 210, ? ]
[ 90123241791111 , 93551622, 121074, 3111, ? ]
and which one is not like the
others… ?
• Thinking loopily and cumulativelysounds natural enough to me!for a while +=
Schedule
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
Self-altering statements?
Shortcuts for changing variables:
age = 41
age = age + 1
amoebas = 100000;amoebas = amoebas * 2
hwToGo = 8;hwToGo = hwToGo - 1
u235 = 10000000000000u235 = u235 / 2;
age += 1
or, even shortcuttier:
recursion is worse!
fore!
for x in range(8):
print 'x is', x
print 'Phew!'anatomy?
empty?
x unused?
x is assigned each value from this
sequence
the BODY or BLOCK of the for loop runs with that x
Code AFTER the loop will not run until the loop is finished.
1
2
3
4
LOOP back to step 1 for EACH value in the list
Accumulating an answer…
def sum( L ):
""" returns the sum of L's elements """
sum = 0
for x in L:
sum = sum + x
return sum
Finding the sum of a list:
Accumulator! Liar! That's not the sum!
shortcuts?
vs. recursion?
sum every OTHER element?
for loops: selfless vs. selfish
Element-based Loops
sum = 0
for x in L: sum += x
L = [ 42, -10, 4 ]
x
"selfless"
for loops: selfless vs. selfish
Element-based Loops
L = [ 42, -10, 4 ]
x
L = [ 42, -10, 4 ]
i0 1 2
Index-based Loops
sum = 0
for x in L: sum += x
sum = 0
for i in : sum +=
these index-based loops seem so egocentric
for loops: selfless vs. selfish
Element-based Loops
L = [ 42, -10, 4 ]
x
L = [ 42, -10, 4 ]
i0 1 2
Index-based Loops
sum = 0
for x in L: sum += x
sum = 0
for i in range(len(L)): sum += L[i]
L[i]
Perspective on for loops
// 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… */
At the top of a project file …
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!'
Extreme Looping
Anatomy of a while loop:
print 'It keeps on'
while True: print 'going and'
print 'Phew! I\'m done!'
“while” loop
the loop keeps on running as long as this test is True
alternative tests?
This won't print until the while loop finishes - in this case, never!
Making our escape!
import randomescape = 0
while escape != 42: print 'Help! Let me out!' escape = random.choice([41,42,43])
print 'At last!'
how could we make it easier/harder to escape?
how could we count the number of loops we run?
Robot Loops?!
Robots run programs that are variants of this very basic loop:
Robot of the Day...
while True: sense() plan() act()
This is the "spa" architecture: it's almost universal.
Which of those three pieces is the most
difficult!?How to escape ?
import randomescape = 0
while True: print 'Help! Let me out!' escape = random.choice([41,42,43]) if escape == 42: break
print 'At last!'
Give me a break !
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
What does this return?
n = 0 for c in s: if c not in 'aeiou': n += 1return n
def mymin( L ):
Write a loop to find and return the min of a list, LL is a list of numbers.
while N > 1: if N%2==0: N /= 2 else: N = 3*N+1
how could you "accumulate" the minimum?
def cc( s ):
>>> cc( 'forty-two' )
def odd( N ):
steps = 0
steps += 1
return steps
>>> odd( 3 )What does this return?
Extra!
n = 0 for c in s: if c not in 'aeiou': n += 1return n
def cc( s ):
>>> cc( 'forty-two' )
What does this return?
Extra!
while N > 1: if N%2==0: N /= 2 else: N = 3*N+1
def odd( N ):
steps = 0
steps += 1
return steps
>>> odd( 3 )
Homework 3
Sequences… #2
What is this stuff?
Hooray… Sanity!
or you could be saying both…
Sound… #3
Graphics… #4
one note on these...
111211211111221312211?
When does the first 4 appear?
str versus float or int
Look-And-Say Sequences(aka “Read-It-And-Weep”)
Representing Sound
continuous plot of air pressure vs. time
samples taken every ~ 1/22050th of a
second
Each sample is measured on a scale from -32,768 to 32,767.
(This fits into 2 bytes.)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.
sampling
quantization
storage
physics
pulse code modulation = PCM data
Python's Etch-a-Sketch
from turtle import *
Be SURE to start IDLE with "no subprocess"
(Step 2) Enter idle –n &
Then, you can type
(Step 1) menus: Go – Utilities – Terminal
Start this!
Mac instructions... Windows instructions...
(Step 1) Go to the Start menu's search field
(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
Hit return; you'll see a console window and IDLE open.
Python's Etch-a-Sketch
Turtle Canvasreset()
left(90)
forward(50)
right(90)
backward(50)
down() or up()
color('green')
tracer(1) or tracer(0)
width(5)
and lots more!
www.cs.hmc.edu/twiki/bin/view/CS5/TurtleDirections
for turtle installation and help
degrees!
states if the pen draws or not
states if the pen animates
or not
from turtle import *
(0,0)
win
dow
_hei
ght(
)
window_width()
(42,42)
Recursive Graphics
def tri(): """ draws a polygon """ forward(100) left(120) forward(100) left(120) forward(100) left(120)
there is no tri … Could we tri this with recursion?(1)
Could we create any regular n-gon?(2)
I don't know about tri, but there sure's NO return … !
def tri( ): """ draws a polygon """
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)
What does chai draw?(1)
Turtle Graphics
Finish rwalk to draw a "stock-market-type" random path of nsteps steps. Use recursion!
(2)
Name(s):
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'
Ex Cr: How could you make it a bull (or a bear) market?
one possible result of rw(20)
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)
What does chai draw?(1)
How could you add more to each end?
Why are there two identical commands in a row?
Finish rwalk to draw a "stock-market-type" random path of nsteps steps. (2)
one possible result of rw(20)
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'
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?
hw3pr4 spiral
100
90
81
72.9
spiral( initLength, angle, multiplier )
close-up of innermost part of the spiral…
spiral( 100, 90, 0.9 )
hw3pr4 svTree
svTree( trunkLength, levels )
svTree( 100, 4 )
I wonder what happened to the leaves on that tree… ?
Level 1
Level 2
Level 3
Level 4
hw2pr3 spiral
100
90
81
72.9
spiral( initLength, angle, multiplier )
close-up of innermost part of the spiral…
spiral( 100, 90, 0.9 )
hw2pr3 svTree
svTree( trunkLength, levels )
svTree( 100, 4 )
I wonder what happened to the leaves on that
tree… ?
Level 1
Level 2
Level 3
Level 4
The Koch curve
snowflake( 100, 0 ) snowflake( 100, 1 ) snowflake( 100, 2 )
snowflake( 100, 3 ) snowflake( 100, 4 ) snowflake( 100, 5 )
CGI == Python + Web
a very common technology for webapplications is the Common Gateway Interface or CGI
webserver
Apache
browser
FirefoxPython Last weekThis week
Next weekNext week
any programs!
CGI == Python + Web
Basic idea
Python
Your Python file prints the HTML page you want!
This week
CGI
#!C:/Python27/python.exe
import cgiimport cgitb; cgitb.enable()
print "Content-Type: text/html; \charset=ISO-8859-1\n\n"print print """<html><body><h1>Hello from Python!</h1></body></html>"""
Lab/HW time
I will be happy to help get your webserver
running Python scripts.
– That will help a lot with problem #1!
Have fun!
Monty 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" ?
Seeing 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!'
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 ==
Clearer Vision
T. T. Securities (TTS)
Input stock prices for a number of days in a row, and then analyze that data… .
Input stock prices for a number of days in a row, and then analyze that data… .
Software
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) QuitEnter your choice:
T. T. Securities (TTS)
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) QuitEnter 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
(L[i] - Lav)2
len(L)i
def stdev( 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) QuitEnter your choice:
Investment analysis for the 21st century…
Software
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) QuitEnter your choice:
Hardware
T. T. Securities (TTS)
Investment analysis for the 21st century…
Software
Menu
Hardware
(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) QuitEnter your choice:
T. T. Securities (TTS)
The TTS advantage!
Your stock's prices:
The TTS investment strategy:
L = [ 40, 80, 10, 30, 27, 52, 5, 15 ]
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.
def minday( L ):
min = L[0]
for x in L:
if x < min:
min = x
return x
Alter this code to return the index of L's minimum.
Example:
>>> minday( [9,8,1,7] )
2
min-value loop
Alter this code to return the index of L's minimum.
using an index-based loop
def minday( L ):
min = L[0]
for :
if < min:
min =
return
INDEX-BASED LOOP
Example:
>>> minday( [9,8,1,7] )
2
>>> diff( [7,3],[0,6] )
1
for x in range(3):
for y in range(3):
print x, y
def diff( X, Y ):
Return the minimum difference between one value from X and one value from Y.
X and Y will be lists of numbers
Hint: adapt this code
Only consider unsigned differences.
Example:
Extra (!) 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 9’s…
1/1 + 1/2 + … + 1/8 + 1/9 + … +1/18 + 1/19 + … + 1/88 + 1/89 + 1/90 + 1/91 + …
Diverges!
???
???
iPhone, geohot, and Von Neumann
George Hotz's iPhone
In red: one memory-access bit
After
Before
soldered to be +1.8v (1)
iPhone, geohot, and Von Neumann
George Hotz's iPhone
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.
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.
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.
The 4 32-bit memory locations it checks are
10100000000000000000000000110000101000000000000010100101101000001010000000000001010111000101100010100000000000010111001101110000
0xA0000030
0xA000A5A0
0xA0015C58
0xA0017370
hex binary
1
10100000000001000000000000110000101000000000010010100101101000001010000000000101010111000101100010100000000001010111001101110000
The memory locations it actually checks are thus
public static double sum(double[] A){ double s = 0.0;
for ( {
} return s;}
public static double average(double[] A)
“Extra Credit”: How concise can this method be?
Finish these two methods… “Quiz”• This method returns the sum of the elements in the input array.
• This method returns the average of the elements in 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 ?!
• This method returns the maximum element from the input array.
Loopy thinking
s = 'gattacaaggtaaaatgca'0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
How could we find the longest sequence of 'a's ?
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 ?
Loopy thinking
s = 'gattacaaggtaaaatgca'0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
How could we find the longest sequence of 'a's ?
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 ?
s = 'gattacaaggtaaaatgca' N = 0for i in range(0,len(s)): if s[i] == 'a': N = N + 1
print 'N is', N
Loopy thinking
s = 'gattacaaggtaaaatgca'0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
How could we find the longest sequence of 'a's ?
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 ?
s = 'gattacaaggtaaaatgca' N = 0for i in range(0,len(s)): if s[i] == 'a' or s[i] == 't': N = N + 1
print 'N is', N
Loopy thinking
s = 'gattacaaggtaaaatgca'0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
How could we find the longest sequence of 'a's ?
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 ?
s = 'gattacaaggtaaaatgca' N = 0for i in range(1,len(s)): if s[i] == 'a' and s[i-1] == 't': N = N + 1
print 'N is', N
Loopy thinking
s = 'gattacaaggtaaaatgca'0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
How could we find the longest sequence of 'a's ?
Planning in "pseudocode"
s = 'gattacaaggtaaaatgca'0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
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'
Keep track of CurRun, MaxRun
Planning in "pseudocode"
s = 'gattacaaggtaaaatgca'0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
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'
Keep track of CurRun, MaxRun
Start a Run! CurRun = 1
Continue our run! CurRun = CurRun + 1Check for a new maximum…
Planning in "pseudocode"
s = 'gattacaaggtaaaatgca'0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
MAX = 0cur = 0for i in range(0,len(s)): if s[i] == 'a': if s[i-1] != 'a': cur = 1 else: cur = cur + 1 if cur > MAX: MAX = cur print 'Max is', MAX
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'
Keep track of CurRun, MaxRun
Start a Run!
Continue our run!
Check for a new maximum…
Quiz, part 2
0 1 2 3 6 7 14 15 30
Write any loop to print the first N terms of
N terms total
7 9 11 13 15 17 …
N terms total
Write an index-based loop to print the first N terms of
def seven(N):
for i in range(N):
feel free to add an accumulator, if you'd like!
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
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
Why Assembly Language ?
It’s only the foolish that never climb Mt. Fuji -- or that climb it again.
Who writes most of the assembly language used?
the compiler
a program that translates from human-usable language into assembly language and machine langauge
x = 6y = 7z = x*yprint z
the code assembly or byte-code
executable machine code
machine code
loadn r1 6loadn r2 7mul r3 r1 r2write r3
0000 0001 0000 00011000 0010 0001 00010110 0010 0010 00010000 0010 0000 00100000 0000 0000 0000
0000 0001 …0010 0001 …0110 0010 …1000 0001 …
interpreting byte code
Interpreter
Compiler
Who writes
asembly?
people who need to talk to the processors directly…
I think the question is, "Who can spell assembly?"
Von Neumann Architecture
CPU RAMcentral processing unit random access memory
programs stored hereinstructions executed here
Von Neumann bottleneck
read r10
1
2
3
4
5
…6
255
jgtz r1 2
factorial program
r0
…
16 registers,
each 16 bits
r15
they can hold values
from -32768 upto
32767
r1
r2
Program
CounterInstruction
RegisterHolds the current instruction
Holds address of the next instruction
loadn r2 1
mul r2 r2 r1
addn r1 -10
the bus!
write r2
halt
iPhone, geohot, and Von Neumann
George Hotz's iPhone
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.
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 4 32-bit memory locations it checks are
10100000000000000000000000110000101000000000000010100101101000001010000000000001010111000101100010100000000000010111001101110000
0xA0000030
0xA000A5A0
0xA0015C58
0xA0017370
hex binary
iPhone, geohot, and Von Neumann
George Hotz's iPhone
In red: one memory-access bit
After
Before
soldered to be +1.8v (1)
iPhone, geohot, and Von Neumann
George Hotz's iPhone
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.
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.
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.
The 4 32-bit memory locations it checks are
10100000000000000000000000110000101000000000000010100101101000001010000000000001010111000101100010100000000000010111001101110000
0xA0000030
0xA000A5A0
0xA0015C58
0xA0017370
hex binary
1
10100000000001000000000000110000101000000000010010100101101000001010000000000101010111000101100010100000000001010111001101110000
The memory locations it actually checks are thus
Thinking about Hmmm
• Repeated actions occur through jumps
• Functions (and recursion) pretend to have a separate processor on which to work
r1
r2
• Results can be set, reset, and accumulated
add r2 r2 r1
19
2342
Thinking about Hmmm
• Functions (and recursion) pretend to have a separate processor on which to work
"Functional" Programming
results from composing individual functions
recursion is common
abstraction allows humans to think about 1 thing at a time
Examples
Fast matrix multiplicationFast median findingFast Fourier Transform…
I may be seeing the theme here…
Thinking about Hmmm
• Functions (and recursion) pretend to have a separate processor on which to work
"Functional" Programming
"Imperative" Programming
results from composing individual functions
recursion is common
abstraction allows humans to think about 1 thing at a time
Python ~ processor.
variables ~ registers
accumulation is common
jumps & loops require people to do the work of the stack
You mean this is NON-functional programming?!?
Input and typing
What is python thinking ?!?
meters = raw_input('How many m? ')
cm = meters * 100
print 'That is', cm, 'cm.'
I'm thinking I like these units better then light years per
year!
Fix #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!
The type of variable (box) matters!name: meters
type: floatname: cmtype: float
1.0 100.0
Homework 3
Sequences… #1
What is this stuff?
Hooray… Sanity!
or you could be saying both…
Graphics… #2
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? ')
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
I always use input -- but don't quote me on that.