IS 313 Putting loops to work for you

  • Slides: 101
Download presentation
IS 313: Putting loops to work for you What's next? [ -35, -24, -13,

IS 313: Putting loops to work for you What's next? [ -35, -24, -13, -2, 9, 20, 31, ? ] [ 26250, 5250, 1050, 210, ? ] [ 1, 11, 21, 1211, 111221, ? ] and which one is not like the others… ? [ 2, 222, ? ] [ 90123241791111 , 93551622, 121074, 3111, ? ] • Thinking loopily for a while and cumulatively sounds natural enough to me! +=

Schedule 9/27 9/28 10/4 10/5 10/11 10/12 10/18 10/29 10/25 10/26 Loops, some graphics,

Schedule 9/27 9/28 10/4 10/5 10/11 10/12 10/18 10/29 10/25 10/26 Loops, some graphics, and webapps Homework #2 due Maximizing… and webforms Homework #3 due Language-processing on the web? Homework #4 due No class this day! No HW due this day! Objects & small projects Homework #5 due

Self-altering statements? Shortcuts for changing variables: age = 41 age = age + 1

Self-altering statements? Shortcuts for changing variables: age = 41 age = age + 1 amoebas = 100000; amoebas = amoebas * 2 hw. To. Go = 8; hw. To. Go = hw. To. Go - 1 u 235 = 10000000 u 235 = u 235 / 2; or, even shortcuttier: age += 1 recursion is worse!

fore! for x in range(8): print 'x is', x print 'Phew!' anatomy? empty? x

fore! for x in range(8): print 'x is', x print 'Phew!' anatomy? empty? x unused?

fore! 1 x is assigned each value from this sequence for x in range(8):

fore! 1 x is assigned each value from this sequence for x in range(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 'Phew!' 4 Code AFTER the loop will not run until the loop is finished. anatomy? empty? x unused?

four on for x in range(8): print 'x is', x how about 6*x? sum

four on for x in range(8): print 'x is', x how about 6*x? sum the list? construct the list?

Accumulating an answer… Finding the sum of a list: def sum( L ): """

Accumulating an answer… Finding the sum of a list: def sum( L ): """ returns the sum of L's elements """ sum = 0 Accumulator! Liar! That's not the sum! for x in L: sum = sum + x shortcuts? return sum vs. recursion? sum every OTHER element?

for loops: selfless vs. selfish Element-based Loops sum = 0 for x in L:

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 Index-based Loops sum = 0 for x

for loops: selfless vs. selfish Element-based Loops Index-based Loops sum = 0 for x in L: sum += x for i in sum += : i L = [ 42, -10, 4 ] x 0 1 2 L = [ 42, -10, 4 ] these index-based loops seem so egocentric

for loops: selfless vs. selfish Element-based Loops Index-based Loops sum = 0 for x

for loops: selfless vs. selfish Element-based Loops Index-based Loops sum = 0 for x in L: sum += x for i in range(len(L)): sum += L[i] i L = [ 42, -10, 4 ] x 0 1 2 L = [ 42, -10, 4 ] L[i]

Perspective on for loops At the top of a project file … // Author:

Perspective on for loops At the top of a project file … // Author: // Purpose: // Matt Beaumont To get me out of CS. . . 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

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” loop the

Extreme Looping Anatomy of a while loop: 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, never! alternative tests?

Making our escape! import random escape = 0 while escape != 42: print 'Help!

Making 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?

Procrastination Programming Every while loop can be a while True: loop! - just be

Procrastination Programming Every while loop can be a while True: loop! - just be sure to break!

Robot Loops? ! Robots run programs that are variants of this very basic loop:

Robot Loops? ! Robots run programs that are variants of this very basic loop: while True: sense() plan() act() This is the "spa" architecture: it's almost universal. Robot of the Day. . . Which of those three pieces is the most difficult!? How to escape ?

Give me a break ! import random escape = 0 I'll figure out later

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

Loops aren't just for lists… for c in 'down with CS!': print c

Loops aren't just for lists… for c in 'down with CS!': print c

def cc( s ): n = 0 for c in s: if c not

def cc( s ): n = 0 for c in s: if c not in 'aeiou': n += 1 return n What does this return? >>> cc( 'forty-two' ) def odd( N ): Extra! steps = 0 while N > 1: if N%2==0: N /= 2 else: N = 3*N+1 steps += 1 return steps >>> odd( 3 ) What does this return? Write a loop to find and return the min of a list, L def mymin( L ): L is a list of numbers. how could you "accumulate" the minimum?

def cc( s ): n = 0 for c in s: if c not

def cc( s ): n = 0 for c in s: if c not in 'aeiou': n += 1 return n >>> cc( 'forty-two' ) What does this return?

Extra! def odd( N ): steps = 0 while N > 1: if N%2==0:

Extra! def odd( N ): steps = 0 while N > 1: if N%2==0: N /= 2 else: N = 3*N+1 steps += 1 return steps >>> odd( 3 )

def min( L ): L is a list of numbers.

def min( L ): L is a list of numbers.

Homework 3 Hooray… Sanity! Sequences… #2 one note on these. . . What is

Homework 3 Hooray… Sanity! Sequences… #2 one note on these. . . What is this stuff? or you could be saying both… Sound… #3 Graphics… #4

Look-And-Say Sequences (aka “Read-It-And-Weep”) 1 11 21 1211 111221 312211 ? str versus float

Look-And-Say Sequences (aka “Read-It-And-Weep”) 1 11 21 1211 111221 312211 ? str versus float or int When does the first 4 appear?

Homework 3 Sequences… #2 or you could be saying both… Sound… #3 Graphics… #4

Homework 3 Sequences… #2 or you could be saying both… Sound… #3 Graphics… #4 DEMO!

Representing Sound physics continuous plot of air pressure vs. time sampling samples taken every

Representing Sound physics continuous plot of air pressure vs. time sampling samples taken every ~ 1/22050 th of a second quantization Each sample is measured on a scale from -32, 768 to 32, 767. (This fits into 2 bytes. ) storage These two bytes are called a frame. Raw audio data - such as what is written to the surface of a CD - is simply a list of these frames. pulse code modulation = PCM data

Homework 3 Sequences… #2 or you could be saying both… Sound… #3 Graphics… #4

Homework 3 Sequences… #2 or you could be saying both… Sound… #3 Graphics… #4 DEMO!

Etch-a-Sketch ? www. gvetchedintime. com No way this is real… but it is !

Etch-a-Sketch ? www. gvetchedintime. com No way this is real… but it is !

Python's Etch-a-Sketch Be SURE to start IDLE with "no subprocess" Mac instructions. . .

Python's Etch-a-Sketch Be SURE to start IDLE with "no subprocess" Mac instructions. . . (Step 1) menus: Go – Utilities – Terminal Windows instructions. . . (Step 1) Go to the Start menu's search field Start this! (Step 2) Type or paste the full path to IDLE If you used the standard install, it will be (Step 2) Enter idle –n & C: Python 27Libidlelibidle. pyw -n Hit return; you'll see a console window and IDLE open. Then, you can type from turtle import *

Python's Etch-a-Sketch from turtle import * Turtle Canvas reset() left(90) degrees! forward(50) (42, 42)

Python's Etch-a-Sketch from turtle import * Turtle Canvas reset() left(90) degrees! forward(50) (42, 42) backward(50) states if the pen draws or not down() or up() color('green') states if the pen animates or not window_height() right(90) (0, 0) tracer(1) or tracer(0) width(5) and lots more! www. cs. hmc. edu/twiki/bin/view/CS 5/Turtle. Directions for turtle installation and help window_width()

Recursive Graphics there is no tri … def tri(): """ draws a polygon """

Recursive Graphics there is no tri … def tri(): """ draws a polygon """ forward(100) left(120) (1) Could we tri this with recursion? def tri( ): """ draws a polygon """ (2) Could we create any regular n-gon? I don't know about tri, but there sure's NO return … !

Name(s): (1) What does chai draw? Turtle Graphics (2) Finish rwalk to draw a

Name(s): (1) What does chai draw? Turtle Graphics (2) Finish rwalk to draw a "stock-market-type" random path of nsteps. Use recursion! from random import * def rw(nsteps): """ moving for nsteps, randomly 45 deg. left/up or right/down """ if nsteps == 0: return if choice(['left', 'right']) == 'left': def chai(size): """ mystery! """ forward(size) left(90) forward(size/2. 0) right(90) backward(size) else: # 'right' one possible result of rw(20) Ex Cr: How could you make it a bull (or a bear) market?

(1) What does chai draw? def chai(size): """ mystery! """ forward(size) left(90) forward(size/2. 0)

(1) What does chai draw? def chai(size): """ mystery! """ forward(size) 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?

(2) Finish rwalk to draw a "stock-market-type" random path of nsteps. from random import

(2) Finish rwalk to draw a "stock-market-type" random path of nsteps. from random import * def rw(nsteps): """ moving for nsteps, randomly 45 deg. left/up or right/down """ if nsteps == 0: return if choice(['left', 'right']) == 'left': else: # 'right' one possible result of rw(20) What if we didn't turn back to face forward each time? Ex Cr: How could you make it a bull (or a bear) market?

hw 3 pr 4 spiral 81 72. 9 90 close-up of innermost part of

hw 3 pr 4 spiral 81 72. 9 90 close-up of innermost part of the spiral… spiral( 100, 90, 0. 9 ) 100 spiral( init. Length, angle, multiplier )

hw 3 pr 4 sv. Tree Level 1 Level 2 Level 3 Level 4

hw 3 pr 4 sv. Tree Level 1 Level 2 Level 3 Level 4 sv. Tree( 100, 4 ) I wonder what happened to the leaves on that tree… ? sv. Tree( trunk. Length, levels )

hw 2 pr 3 spiral 81 72. 9 90 close-up of innermost part of

hw 2 pr 3 spiral 81 72. 9 90 close-up of innermost part of the spiral… spiral( 100, 90, 0. 9 ) 100 spiral( init. Length, angle, multiplier )

hw 2 pr 3 sv. Tree Level 1 Level 2 Level 3 Level 4

hw 2 pr 3 sv. Tree Level 1 Level 2 Level 3 Level 4 sv. Tree( 100, 4 ) I wonder what happened to the leaves on that tree… ? sv. Tree( trunk. Length, levels )

The Koch curve snowflake( 100, 0 ) snowflake( 100, 3 ) snowflake( 100, 1

The Koch curve snowflake( 100, 0 ) snowflake( 100, 3 ) snowflake( 100, 1 ) snowflake( 100, 4 ) snowflake( 100, 2 ) snowflake( 100, 5 )

CGI == Python + Web a very common technology for webapplications is the Common

CGI == Python + Web a very common technology for webapplications is the Common Gateway Interface or CGI Python This week Apache Next week any programs! Last week Firefox Next week webserver browser

CGI == Python + Web Basic idea Your Python file prints the HTML page

CGI == Python + Web Basic idea Your Python file prints the HTML page you want! #!C: /Python 27/python. exe import cgitb; cgitb. enable() print "Content-Type: text/html; charset=ISO-8859 -1nn" print """ <html> <body> <h 1>Hello from Python!</h 1> </body> </html> """ Python This week CGI

Lab/HW time I will be happy to help get your webserver running Python scripts.

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 Let’s make a deal ’ 63 -’ 86 Sept. 1990 inspiring the

Monty Hall Let’s make a deal ’ 63 -’ 86 Sept. 1990 inspiring the “Monty Hall paradox”

Monty Hall Getting the user's input: answer = raw_input( 'What is your name? '

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 print "(1) print "(2) print "(9)

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:

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… Light. Path, September 1999

the gift… Light. Path, September 1999

watching the charts… Light. Path, six months later…

watching the charts… Light. Path, six months later…

"brokerage" seems apt… Light. Path, now…

"brokerage" seems apt… Light. Path, now…

T. T. Securities (TTS) Input stock prices for a number of days in a

T. T. Securities (TTS) Input stock prices for a number of days in a row, then analyze that data…. and

T. T. Securities (TTS) Input stock prices for a number of days in a

T. T. Securities (TTS) Input stock prices for a number of days in a row, 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 and

Functions There a number of formulas, but we will use this one: functions def

Functions There 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 a number of formulas, but we will use this one: functions

Standard Deviation There 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 21 st century… Hardware Menu (0)

T. T. Securities (TTS) Investment analysis for the 21 st 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 21 st century… Hardware Menu (0)

T. T. Securities (TTS) Investment analysis for the 21 st 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,

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. Example: >>> minday( [9,

Alter this code to return the index of L's minimum. Example: >>> minday( [9, 8, 1, 7] ) 2 def minday( L ): min = L[0] for x in L: if x < min: min = x return x min-value loop

Example: Alter this code to return the index of L's minimum. >>> minday( [9,

Example: Alter this code to return the index of L's minimum. >>> minday( [9, 8, 1, 7] ) 2 def minday( L ): min = L[0] for : if < min: min = return INDEX-BASED LOOP using an indexbased loop

What does this code print? for x in range(3): for y in range(3): print

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

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

Lab & Questions

Lab & Questions

Extra (!) funky series Diverges! • Harmonic Sequence: 1/1 + 1/2 + 1/3 +

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 + …

Hw 8 Pr 3 Monte Carlo p A engineering challenge: to estimate p using

Hw 8 Pr 3 Monte Carlo p A engineering challenge: to estimate p using everyday items. . .

Easy as p (1, 1) Visualize: (-1, -1)

Easy as p (1, 1) Visualize: (-1, -1)

i. Phone, geohot, and Von Neumann George Hotz's i. Phone Before After In red:

i. Phone, geohot, and Von Neumann George Hotz's i. Phone Before After In red: one memory-access bit soldered to be +1. 8 v (1)

i. Phone, geohot, and Von Neumann When starting up, the phone checks 4 locations

i. Phone, 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 0 x. A 0000030 0 x. A 000 A 5 A 0 0 x. A 0015 C 58 0 x. A 0017370 101000000000000110000 10100000001010010110100000010101110001011000 10100000010111001101110000 1 George Hotz's i. Phone 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 101000000000000110000 10100000100101101000001010101110001011000 101000001010111001101110000 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.

i. Phone, geohot, and Von Neumann George Hotz's i. Phone the trade

i. Phone, geohot, and Von Neumann George Hotz's i. Phone the trade

“Quiz” Finish these two methods… • This method returns the sum of the elements

“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

• 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

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

Loopy thinking 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 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

Loopy thinking 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 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

Loopy thinking 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 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

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

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 Cur. Run, Max. Run 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

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 Cur. Run, Max. Run Loop through the string: if we do see an 'a' if the PREVIOUS letter is NOT an 'a' Start a Run! Cur. Run = 1 if the PREVIOUS letter IS an 'a' Continue our run! Cur. Run = Cur. Run + 1 Check for a new maximum…

Planning in "pseudocode" 0 1 2 3 4 5 6 7 8 9 10

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 Cur. Run, Max. Run print 'Max is', MAX

Challenge Example: >>> fib(11) 1 1 2 3 5 Print the first N numbers

Challenge Example: >>> fib(11) 1 1 2 3 5 Print the first N numbers in this series… 8 13 21 34 55 89

Write an index-based loop to print the first N terms of N terms total

Write an index-based loop to print the first N terms of N terms total 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 Write any loop to print the first N terms of N terms total 0 1 2 3 6 7 14 15 30

input vs. raw_input reply = raw_input('Enter a string and I'll tell you what I

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

Why Assembly Language ? It’s only the foolish that never climb Mt. Fuji --

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

the compiler a program that translates from human-usable language into assembly language and machine langauge Compiler x = 6 y = 7 z = x*y print z the code loadn r 1 6 loadn r 2 7 mul r 3 r 1 r 2 write r 3 assembly or byte-code Interpreter 0000 1000 0110 0000 0001 0010 0000 0001 0010 0000 executable machine code 0000 0010 0110 1000 0001 0010 0001 … … machine code interpreting byte code

Register r 0 is always 0.

Register r 0 is always 0.

Pure jumps not allowed! Assembly language jump # Fortran, C, C++, Basic, … GOTO

Pure jumps not allowed! Assembly language jump # Fortran, C, C++, Basic, … GOTO #

Who writes asembly? I think the question is, "Who can spell assembly? " people

Who writes asembly? I think the question is, "Who can spell assembly? " people who need to talk to the processors directly…

Von Neumann Architecture instructions executed here CPU central processing unit programs stored here the

Von Neumann Architecture instructions executed here CPU central processing unit programs stored here the bus! Program Counter Holds address of the next instruction Instruction Register Holds the current instruction 0 r 1 r 2 r 15 … RAM Von Neumann bottleneck 16 registers, each 16 bits they can hold values from -32768 upto 32767 random access memory 0 read r 1 1 loadn r 2 1 2 mul r 2 r 1 3 addn r 1 -1 4 jgtz r 1 2 5 write r 2 6 halt … 255 factorial program

i. Phone, geohot, and Von Neumann George Hotz's i. Phone

i. Phone, geohot, and Von Neumann George Hotz's i. Phone

i. Phone, geohot, and Von Neumann George Hotz's i. Phone Before In red: one

i. Phone, geohot, and Von Neumann George Hotz's i. Phone Before In red: one memory-access bit

i. Phone, geohot, and Von Neumann When starting up, the phone checks 4 locations

i. Phone, 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 0 x. A 0000030 0 x. A 000 A 5 A 0 0 x. A 0015 C 58 0 x. A 0017370 101000000000000110000 10100000001010010110100000010101110001011000 10100000010111001101110000 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. George Hotz's i. Phone

i. Phone, geohot, and Von Neumann George Hotz's i. Phone Before After In red:

i. Phone, geohot, and Von Neumann George Hotz's i. Phone Before After In red: one memory-access bit soldered to be +1. 8 v (1)

i. Phone, geohot, and Von Neumann When starting up, the phone checks 4 locations

i. Phone, 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 0 x. A 0000030 0 x. A 000 A 5 A 0 0 x. A 0015 C 58 0 x. A 0017370 101000000000000110000 10100000001010010110100000010101110001011000 10100000010111001101110000 1 George Hotz's i. Phone 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 101000000000000110000 10100000100101101000001010101110001011000 101000001010111001101110000 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.

i. Phone, geohot, and Von Neumann George Hotz's i. Phone the trade

i. Phone, geohot, and Von Neumann George Hotz's i. Phone the trade

Thinking about Hmmm • Functions (and recursion) pretend to have a separate processor on

Thinking about Hmmm • Functions (and recursion) pretend to have a separate processor on which to work • Repeated actions occur through jumps r 1 19 r 2 42 23 • Results can be set, reset, and accumulated add r 2 r 1

Thinking about Hmmm • Functions (and recursion) pretend to have a separate processor on

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 multiplication Fast median finding Fast Fourier Transform … I may be seeing theme here…

Thinking about Hmmm • Functions (and recursion) pretend to have a separate processor on

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 Python ~ processor. variables ~ registers recursion is common accumulation is common abstraction allows humans to think about 1 thing at a time jumps & loops require people to do the work of the stack You mean this is NONfunctional programming? !?

Input and typing meters = raw_input('How many m? ') cm = meters * 100

Input 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!

Fix #1: use a type converter meters = float(raw_input('How many m? ')) cm =

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!

Homework 3 Sequences… #1 Hooray… Sanity! What is this stuff? Graphics… #2 or you

Homework 3 Sequences… #1 Hooray… Sanity! What is this stuff? Graphics… #2 or you could be saying both…

Fix #2: use input() # gets processed input from user meters = input('How many

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

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