Presentation is loading. Please wait.

Presentation is loading. Please wait.

IS 313: Putting loops to work for you What's next? [ 1, 11, 21, 1211, 111221, ? ] [ -35, -24, -13, -2, 9, 20, 31, ? ] [ 2, 22, 222, ? ] [ 26250, 5250,

Similar presentations


Presentation on theme: "IS 313: Putting loops to work for you What's next? [ 1, 11, 21, 1211, 111221, ? ] [ -35, -24, -13, -2, 9, 20, 31, ? ] [ 2, 22, 222, ? ] [ 26250, 5250,"— Presentation transcript:

1 IS 313: Putting loops to work for you What'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 cumulatively sounds natural enough to me! for a while +=

2 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

3 Self-altering statements? Shortcuts for changing variables: age = 40 age = age + 1 amoebas = 100000; amoebas = amoebas * 2 hwToGo = 8; hwToGo = hwToGo - 1 u235 = 10000000000000 u235 = u235 / 2; age += 1 or, even shortcuttier: recursion is worse!

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

5 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. 1 2 3 4 LOOP back to step 1 for EACH value in the list

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

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

8 for loops: selfless vs. selfish Element-based Loops sum = 0 for x in L: sum += x L = [ 42, -10, 4 ] x "selfless"

9 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

10 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]

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

12 Extreme Looping What does this code do? print 'It keeps on' while True: print 'going and' print 'Phew! I\'m done!'

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

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

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

16 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 )

17 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' )

18 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 )

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

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

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

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

23 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 1.0 100.0

24 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.

25 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.

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

27 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

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

29 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! 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 or wynnturtle from turtle import *

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

31 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 """

32 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)

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

34 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'

35 hw3pr2 spiral 100 90 81 72.9 spiral( initLength, angle, multiplier ) close-up of innermost part of the spiral… spiral( 100, 90, 0.9 )

36 hw3pr2 svTree svTree( trunkLength, levels ) svTree( 100, 4 ) and more! (if you want) I wonder what happened to the leaves on that tree… ?

37 hw3pr2 your choice… www.cs.hmc.edu/twiki/bin/view/CS5/TurtleDirections more?

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

39 Homework 2 Functions #1#1 You may use loops or recursion - whichever you'd like… Monty Hall #2#2 Is there a door #3?

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

41 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" ?

42 Lab: Homework #2 or #3…

43 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!'

44 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

45 the gift… LightPath, September 1999

46 watching the charts… LightPath, six months later…

47 "brokerage" seems apt… LightPath, now…

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

49 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)

50 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 )

51 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:

52 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)

53 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)

54 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.

55 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

56 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

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

58 >>> 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:

59 Lab & Questions

60 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! ???

61 Monte Carlo  A engineering challenge: to estimate  using everyday items... Hw8 Pr3

62 Visualize: Easy as  (-1,-1) (1,1)

63 iPhone, geohot, and Von Neumann George Hotz's iPhone In red: one memory-access bit After Before soldered to be +1.8v ( 1 )

64 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 10100000000000000000000000110000 10100000000000001010010110100000 10100000000000010101110001011000 10100000000000010111001101110000 0xA0000030 0xA000A5A0 0xA0015C58 0xA0017370 hex binary 1 10100000000001000000000000110000 10100000000001001010010110100000 10100000000001010101110001011000 10100000000001010111001101110000 The memory locations it actually checks are thus

65 iPhone, geohot, and Von Neumann George Hotz's iPhone the trade

66 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.

67 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.

68 Loopy thinking s = 'gattacaaggtaaaatgca' 0123456789 101112131415161718 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 ?

69 Loopy thinking s = 'gattacaaggtaaaatgca' 0123456789 101112131415161718 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

70 Loopy thinking s = 'gattacaaggtaaaatgca' 0123456789 101112131415161718 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

71 Loopy thinking s = 'gattacaaggtaaaatgca' 0123456789 101112131415161718 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

72 Loopy thinking s = 'gattacaaggtaaaatgca' 0123456789 101112131415161718 How could we find the longest sequence of 'a' s ?

73 Planning in "pseudocode" s = 'gattacaaggtaaaatgca' 0123456789 101112131415161718 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

74 Planning in "pseudocode" s = 'gattacaaggtaaaatgca' 0123456789 101112131415161718 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…

75 Planning in "pseudocode" s = 'gattacaaggtaaaatgca' 0123456789 101112131415161718 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…

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

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

78 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

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

80 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 r3 0000 0001 1000 0010 0001 0001 0110 0010 0010 0001 0000 0010 0000 0000 0000 0001 … 0010 0001 … 0110 0010 … 1000 0001 … interpreting byte code Interpreter Compiler

81 Register r0 is always 0.

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

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

84 Von Neumann Architecture CPU RAM central processing unit random access memory programs stored here instructions executed here Von Neumann bottleneck read r1 0 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 Counter Instruction Register Holds the current instruction Holds address of the next instruction loadn r2 1 mul r2 r2 r1 addn r1 -1 0 the bus! write r2 halt

85 iPhone, geohot, and Von Neumann George Hotz's iPhone

86 iPhone, geohot, and Von Neumann George Hotz's iPhone In red: one memory-access bit Before

87 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 10100000000000000000000000110000 10100000000000001010010110100000 10100000000000010101110001011000 10100000000000010111001101110000 0xA0000030 0xA000A5A0 0xA0015C58 0xA0017370 hex binary

88 iPhone, geohot, and Von Neumann George Hotz's iPhone In red: one memory-access bit After Before soldered to be +1.8v ( 1 )

89 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 10100000000000000000000000110000 10100000000000001010010110100000 10100000000000010101110001011000 10100000000000010111001101110000 0xA0000030 0xA000A5A0 0xA0015C58 0xA0017370 hex binary 1 10100000000001000000000000110000 10100000000001001010010110100000 10100000000001010101110001011000 10100000000001010111001101110000 The memory locations it actually checks are thus

90 iPhone, geohot, and Von Neumann George Hotz's iPhone the trade

91 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 r1 19 23 42

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

93 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?!?


Download ppt "IS 313: Putting loops to work for you What's next? [ 1, 11, 21, 1211, 111221, ? ] [ -35, -24, -13, -2, 9, 20, 31, ? ] [ 2, 22, 222, ? ] [ 26250, 5250,"

Similar presentations


Ads by Google