1 / 101

IS 313 : Putting loops to work for you

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, ? ].

Download Presentation

IS 313 : Putting loops to work for you

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 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, ? ] • Thinking loopily and cumulatively += for a while sounds natural enough to me!

  2. 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 onthe 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

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

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

  5. fore! x is assigned each value from this sequence 1 for x in range(8): print'x is', x print'Phew!' 3 LOOP back to step 1 for EACH value in the list the BODY or BLOCK of the for loop runs with that x 2 anatomy? empty? x unused? Code AFTER the loop will not run until the loop is finished. 4

  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… Finding the sum of a list: def sum( L ): """ returns the sum of L's elements """ sum = 0 for x in L: sum = sum + x return sum 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 Index-based Loops sum = 0 for x in L: sum += x sum = 0 for i in : sum += i 1 2 0 L = [ 42, -10, 4 ] L = [ 42, -10, 4 ] x these index-based loops seem so egocentric

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

  11. Perspective on for loops At the top of a project file … // 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… */ and it is possible to avoid them entirely…

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

  13. Extreme Looping Anatomy of a while loop: the loop keeps on running as long as this test is True print'It keeps on' whileTrue: print'going and' print'Phew! I\'m done!' “while” loop This won't print until the while loop finishes - in this case, never! alternative tests?

  14. Making our escape! import random escape = 0 whileescape != 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?

  15. Procrastination Programming Every while loop can be a whileTrue: loop! - just be sure to break!

  16. 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. Which of those three pieces is the most difficult!? Robot of the Day... How to escape ?

  17. Give me a break ! import random escape = 0 whileTrue: print'Help! Let me out!' escape = random.choice([41,42,43]) if escape == 42: break print'At last!' 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 comparereturn

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

  19. def cc( s ): Write a loop to find and return the min of a list, L n = 0 for c in s: if c not in'aeiou': n += 1 return n L is a list of numbers. def mymin( L ): how could you "accumulate" the minimum? 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 What does this return? >>> odd( 3 )

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

  21. 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 )

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

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

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

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

  26. Representing Sound physics continuous plot of air pressure vs. time sampling samples taken every ~ 1/22050th 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

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

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

  29. Python's Etch-a-Sketch Be SURE to start IDLE with "no subprocess" Mac instructions... Windows instructions... (Step 1) Go to the Start menu's search field (Step 1) menus: Go – Utilities – Terminal Start this! (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 (Step 2) Enter idle –n & Hit return; you'll see a console window and IDLE open. Then, you can type from turtle import *

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

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

  32. Turtle Graphics Name(s): Finish rwalk to draw a "stock-market-type" random path of nsteps steps. Use recursion! (1) What does chai draw? (2) 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' 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) Ex Cr: How could you make it a bull (or a bear) market? one possible result of rw(20)

  33. (1) What does chai draw? 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) Why are there two identical commands in a row? How could you add more to each end?

  34. (2) Finish rwalk to draw a "stock-market-type" random path of nsteps steps. 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' 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?

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

  36. hw3pr4 svTree Level 1 Level 2 Level 3 Level 4 svTree( 100, 4 ) I wonder what happened to the leaves on that tree… ? svTree( trunkLength, levels )

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

  38. hw2pr3 svTree Level 1 Level 2 Level 3 Level 4 svTree( 100, 4 ) I wonder what happened to the leaves on that tree… ? svTree( trunkLength, levels )

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

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

  41. CGI == Python + Web Basic idea Your Python file prints the HTML page you want! #!C:/Python27/python.exe import cgi import 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> """ This week Python CGI

  42. 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!

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

  44. 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" ?

  45. 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 """ whileTrue: menu() uc = input('Which option? ') print'The inner eye does not see upon command!'

  46. Clearer Vision def seer(): """ handles user input for our menu """ whileTrue: menu() uc = input('Which option? ') print'The inner eye does not see upon command!' if uc ==

  47. the gift… LightPath, September 1999

  48. watching the charts… LightPath, six months later…

  49. "brokerage" seems apt… LightPath, now…

More Related