IS 313: Putting loops to work for you What's next? [ 1, 11, 21, 1211, , ? ] [ -35, -24, -13, -2, 9, 20, 31, ? ] [ 2, 22, 222, ? ] [ 26250, 5250, 1050, 210, ? ] [ , , , 3111, ? ] and which one is not like the others… ? Thinking loopily and cumulatively sounds natural enough to me! for a while +=
Schedule 9/30/09Graphics and loops! 10/1/07Homework #2 due 10/7/09Maximizing… and browser apps 10/8/07Homework #3 due 10/14/09Language-processing on the web 10/15/07Homework #4 due - small webapp 10/21/09Fall break! 10/22/07No HW due 10/28/09Objects & larger projects… 10/29/07Homework #5 due
Self-altering statements? Shortcuts for changing variables: age = 40 age = age + 1 amoebas = ; amoebas = amoebas * 2 hwToGo = 8; hwToGo = hwToGo - 1 u235 = u235 = u235 / 2; age += 1 or, even shortcuttier: recursion is worse!
for e! for x in range(8): print 'x is', x print 'Phew!' anatomy? empty? x unused?
for e! 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 LOOP back to step 1 for EACH value in the list
four on for for x in range(8): print 'x is', x how about 6*x? sum the list? construct 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 i 0 12 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 i 0 12 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 random escape = 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?
Loops aren't just for lists… for c in 'down with CS!': print c
What do these two f'ns return? n = 0 for c in s: if c not in 'aeiou': n += 1 return n def min( L ): Write a loop to find and return the min of a list, L L 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 do these two f'ns return? n = 0 for c in s: if c not in 'aeiou': n += 1 return n def cc( s ): >>> cc( 'forty-two' )
What do these two f'ns return? 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 )
def min( L ): L is a list of numbers.
Homework 3 Sequences… #1#1 What is this stuff? Hooray… Sanity! or you could be saying both… Graphics… #2#2
Look-And-Say Sequences (aka “Read-It-And-Weep”) ? When does the first 4 appear? str versus float or int
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: float name: cm type: float
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.
Procrastination Programming Every while loop can be a while True: loop! - just be sure to break !
import random escape = 0 while True: print 'Help! Let me out!' escape = random.choice([41,42,43]) if escape == 42: break print 'At last!' 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
Homework 3 Sequences… #1#1 What is this stuff? Hooray… Sanity! or you could be saying both… Graphics… #2#2
Python's Etch-a-Sketch A new human-computer interface? reset() left(90) forward(50) right(90) backward(50) down() or up() color('green') tracer(1) or tracer(0) width(5) and lots more! for turtle installation and help degrees! states if the pen draws or not states if the pen animates or not or wynnturtle from turtle import *
Etch-a-Sketch ? No way this is real… but it is !
Recursion vs Loops def tri(): """ draws a polygon """ forward(100) left(120) forward(100) left(120) forward(100) left(120) Could we tri this with recursion? (1) Could we create any regular n-gon? (2) This seems like the place for a for ! def tri( ): """ draws a polygon """
def chai(size): """ mystery! """ forward(size) left(90) forward(size/2.0) right(90) forward(size) left(90) forward(size/2.0) right(90) backward(size) What does chai draw? (1) Finish rw to draw a "stock-market-type" random walk of n steps. Use recursion… (2) from random import * def rw(n): """ move for n uniform steps, randomly 45 deg. left/up or right/down """ if n == 0: return if choice(['L','R']) == 'L': # 'Left' else: # 'Right' 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) forward(size) 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 rw to draw a "stock-market-type" random walk of n steps. (2) one possible result of rw(20) Ex Cr: How could you make it a bull (or a bear) market? What if we didn't go back to the starting pose? from random import * def rw(n): """ move for n uniform steps, randomly 45 deg. left/up or right/down """ if n == 0: return if choice(['L','R']) == 'L': # 'Left' else: # 'Right'
hw3pr2 spiral spiral( initLength, angle, multiplier ) close-up of innermost part of the spiral… spiral( 100, 90, 0.9 )
hw3pr2 svTree svTree( trunkLength, levels ) svTree( 100, 4 ) and more! (if you want) I wonder what happened to the leaves on that tree… ?
hw3pr2 your choice… more?
The Koch curve snowflake( 100, 0 )snowflake( 100, 1 ) snowflake( 100, 2 ) snowflake( 100, 3 )snowflake( 100, 4 )snowflake( 100, 5 )
Homework 2 Functions #1#1 You may use loops or recursion - whichever you'd like… Monty Hall #2#2 Is there a door #3?
Monty Hall Let’s make a deal ’63-’86 Sept inspiring the “Monty Hall paradox”
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" ?
Lab: Homework #2 or #3…
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
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….
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) Quit Enter 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) 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 (L[i] - L av ) 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) Quit Enter 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) Quit Enter 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) Quit Enter 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 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
What does this code print? for x in range(3): for y in range(3): print x, y
>>> 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:
Lab & Questions
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! ???
Monte Carlo A engineering challenge: to estimate using everyday items... Hw8 Pr3
Visualize: Easy as (-1,-1) (1,1)
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 xA xA000A5A0 0xA0015C58 0xA hex binary The memory locations it actually checks are thus
iPhone, geohot, and Von Neumann George Hotz's iPhone the trade
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' 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' 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 = 0 for i in range(0,len(s)): if s[i] == 'a': N = N + 1 print 'N is', N
Loopy thinking s = 'gattacaaggtaaaatgca' 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 = 0 for 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' 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 = 0 for 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' How could we find the longest sequence of 'a' s ?
Planning in "pseudocode" s = 'gattacaaggtaaaatgca' 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' 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 + 1 Check for a new maximum…
Planning in "pseudocode" s = 'gattacaaggtaaaatgca' MAX = 0 cur = 0 for 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…
Challenge Print the first N numbers in this series… Example: >>> fib(11)
Quiz, part Write any loop to print the first N terms of N terms total … 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 = 6 y = 7 z = x*y print z the code assembly or byte-code executable machine code machine code loadn r1 6 loadn r2 7 mul r3 r1 r2 write r … … … … interpreting byte code Interpreter Compiler
Register r0 is always 0.
Pure jump s not allowed! Assembly language GOTO #jump # Fortran, C, C++, Basic, …
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 RAM central processing unit random access memory programs stored here instructions executed here Von Neumann bottleneck read r … jgtz r1 2 factorial program r0 … 16 registers, each 16 bits r15 they can hold values from upto r1 r2 Program Counter Instruction Register Holds the current instruction Holds address of the next instruction loadn r2 1 mul r2 r2 r1 addn r the bus! write r2 halt
iPhone, geohot, and Von Neumann George Hotz's iPhone
iPhone, geohot, and Von Neumann George Hotz's iPhone In red: one memory-access bit Before
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 xA xA000A5A0 0xA0015C58 0xA 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 xA xA000A5A0 0xA0015C58 0xA hex binary The memory locations it actually checks are thus
iPhone, geohot, and Von Neumann George Hotz's iPhone the trade
Thinking about Hmmm Repeated actions occur through jump s 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 r
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 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?!?