Presentation is loading. Please wait.

Presentation is loading. Please wait.

IS 313 Tomorrow… IS 313 last week ? 9/20/09 - today: beyond recursion! 9/27/09 - next wk: web technologies, pt 2 Assignment reminders... Which door to.

Similar presentations


Presentation on theme: "IS 313 Tomorrow… IS 313 last week ? 9/20/09 - today: beyond recursion! 9/27/09 - next wk: web technologies, pt 2 Assignment reminders... Which door to."— Presentation transcript:

1 IS 313 Tomorrow… IS 313 last week ? 9/20/09 - today: beyond recursion! 9/27/09 - next wk: web technologies, pt 2 Assignment reminders... Which door to choose? This week...Next week...

2 Computation's Dual Identity name: x type: int LOC: 300 41 "variables as containers" memory location 300 ComputationData Storage name: y type: int LOC: 304 42 memory location 304 accessed through functions… lists and strings…

3 Data: review… How could we get the first element of s ? Suppose s = 'latin' How could we get the rest of s ? (all but the first) What if we then add 'ay' ?

4 # my own function! def dbl( x ): """ returns double its input, x """ return 2*x Comments Docstrings (1)describes overall what the function does, and (2)explains what the inputs mean/are They become part of python's built-in help system! With each function be sure to include one that They begin with # keywords def starts the function return stops it immediately and sends back the return value Some of Python's baggage… Look good to me! Functions: review…

5 # how do you like your coffee? def undo(s): """ this "undoes" its string input, s """ return 'de' + s Functioning with strings and lists… # what does this do? def warp(L): """ L can be any sequence """ return L[1:] + L[0:1] >>> undo(undo('caf')) >>> warp('space') >>> warp('drake')

6 def chop(s): """ mystery! """ return Functioning with strings and lists… def stackup(s): """ mystery! """ return >>> chop('graduate') 'grad' >>> chop(chop('abcd')) 'a' >>> stackup('star') 'starrats' >>> stackup('dumbmob ') 'dumbmob bombmud'

7 # you don't need these comments def chop(s): """ this returns half its string input, s """ return s[:len(s)/2] Functioning with strings and lists… def stackup(s): """ this outputs the original s with the reverse of s tacked onto its end… """ return s + s[::-1] >>> chop('graduate') 'grad' >>> chop(chop('abcd')) 'a' >>> stackup('star') 'starrats' >>> stackup('dumbmob ') 'dumbmob bombmud'

8 Recursion warning: Be sure to watch your head!

9 beyond recursion? Creating general functions that will be useful everywhere (or almost…) building blocks with which to compose…

10 def sum(L): """ input: a list of numbers, L output: L's sum """ if len(L) == 0: return 0.0 else: return L[0] + sum(L[1:]) sum recursively Base Case if the input list has no elements, its sum is zero Recursive Case if L does have an element, add that element's value to the sum of the REST of the list…

11 def sum(L): """ input: a list of numbers, L output: L's sum """ result_so_far = 0.0 for e in L: result_so_far = result_so_far + e return result_so_far sum with loops! Starter value zero, in this case Loop! add e each time! That's it! Like loops? Check out http://docs.python.org/tutorial/controlflow.html

12 Recursion vs. loops? The choice is yours! more loops next week....

13 range, recursively what's cookin' here? excluding hi def range(low,hi): """ input: two ints, low and hi output: list from low up to hi """ if hi <= low: return [] else: return [low] +

14 range, with loops! def range(low,hi): """ input: two ints, low and hi output: list from low up to hi """ result = [] e = low while e < hi: result = result + [e] return result what's cookin' here? excluding hi Starter value empty list, in this case Loop! add [e] each time! Like loops? Check out http://docs.python.org/tutorial/controlflow.html

15 sum and range >>> sum(range(1,101)) Looks sort of scruffy for a 7-year old… !

16 List Comprehensions Is this really the best name Guido Van Rossum could think of?

17 List Comprehensions >>> [ 2*x for x in [0,1,2,3,4,5] ] [0, 2, 4, 6, 8, 10] What is going on here? output input A Loop in a List! and the "running" variable can have any name...

18 List Comprehensions >>> [ 2*x for x in [0,1,2,3,4,5] ] [0, 2, 4, 6, 8, 10] output input A Loop in a List! and the "running" variable can have any name... (1) x takes on each value in the list or string (2) The operation 2*x happens for each x

19 List Comprehensions >>> [ _______ for y in range(6) ] [0, 1, 4, 9, 16, 25] >>> [ __________ for c in 'igotit' ] [True, False, False, False, True, False] output input A Loop in a List!

20 List Comprehensions >>> [ 2*x for x in [0,1,2,3,4,5] ] [0, 2, 4, 6, 8, 10] >>> [ y**2 for y in range(6) ] [0, 1, 4, 9, 16, 25] >>> [ c == 'a' for c in 'go away!' ] [0, 0, 0, 1, 0, 1, 0, 0] Anything you want to happen to each element of a list output input name that takes on the value of each element in turn the list (or string) Is this really the best name Guido Van Rossum could think of? any name is OK!

21 List Comprehensions >>> [ 2*x for x in [0,1,2,3,4,5] ] [0, 2, 4, 6, 8, 10] >>> [ y**2 for y in range(6) ] [0, 1, 4, 9, 16, 25] >>> [ c == 'a' for c in 'go away!' ] [0, 0, 0, 1, 0, 1, 0, 0] Anything you want to happen to each element of a list output input name that takes on the value of each element in turn the list (or string) Makes sense to me! Google's Maps One-hit wonders Lazy lists

22 Raw recursion... def len(L): if L == []: return 0 else: return 1 + len(L[:]) A list comprehension by any other name would be as sweet… def countAs(s): if len(s) == 0: return 0 elif s[0] == 'A': return 1 + countAs(s[1:]) else: return countAs(s[1:]) 7 lines! Aargh! count of 'A's in the string s length of the list L

23 ... vs. List Comprehensions LC = [ ______ for x in L] return sum( LC ) len(L): countAs(s): LC = [ ________ for c in s] return sum( LC ) def I prefer one-liners! suppose s is a string of capital letters

24 vs. List Comprehensions numOdds(L): # of odd elements LC = [ for x in L] return sum( LC ) def sajak(s): LC = [ for c in s] return sum( LC ) # of vowels Remember True == 1 and False == 0 def

25 Try it! Write each of these functions concisely using list comprehensions… Write def count(e,L): Write def lotto(Y,W): input: e, any element L, any list or string output: the # of times L contains e example: count('f', 'fluff') == 3 input: Y and W, two lists of lottery numbers (ints) output: the # of matches between Y & W example: lotto([5,7,42,44],[3,5,7,44]) == 3 Y are your numbers W are the winning numbers Remember True == 1 and False == 0 Extra! def numdivs(N): input: N, an int >= 2 output: the number of positive divisors of N example: numdivs(12) == 6 (1,2,3,4,6,12) How could you use this to compute all of the prime numbers up to P ? LC = [ for x in L ] return sum(LC) don't use e here! use e in here somehow… def primesUpto( P ):

26 Quiz Write def count(e,L): input: e, any element L, any list or string output: the # of times L contains e example: count('f', 'fluff') == 3 Remember True == 1 and False == 0 LC = [ for x in L ] return sum(LC) don't use e here! use e in here somehow…

27 Write def lotto(Y,W): input: Y and W, two lists of lottery numbers (ints) output: the # of matches between Y & W example: lotto([5,7,42,44],[3,5,7,44]) == 3 Y are your numbers W are the winning numbers

28 Extra! def numdivs(N): input: N, an int >= 2 output: the number of positive divisors of N example: numdivs(12) == 6 (1,2,3,4,6,12) How could you use this to compute all of the prime numbers up to P ? def primesUpto( P ): What if you want the divisors themselves? or prime #s?

29 Maya Lin, Architect…

30 "two-by-four landscape" Maya Lin, Computer Scientist…

31 One building block, carefully applied, over 50,000 times… Maya Lin, Computer Scientist…

32 A random aside… import random choice( L ) uniform(low,hi) choice( ['rock', 'paper', 'scissors'] ) uniform(41.9,42.1) chooses 1 element from the sequence L chooses a random float from low to hi allows use of dir(random) and help(random) How likely is this to return 42 ? How would you get a random int from 0 to 9 inclusive? from random import * all random functions are now available!

33 A random function… print the guesses ? return the number of guesses ? from random import * def guess( hidden ): """ guesses the user's hidden # """ compguess = choice( range(100) ) if compguess == hidden: # at last! print 'I got it!' else: guess( hidden ) This is a bit suspicious… slow down…

34 The final version from random import * import time def guess( hidden ): """ guesses the user's hidden # """ compguess = choice( range(100) ) # print 'I choose', compguess # time.sleep(0.05) if compguess == hidden: # at last! # print 'I got it!' return 1 else: return 1 + guess( hidden )

35 The two Monte Carlos Monte Carlo casino, Monaco Making random numbers work for you! Monte Carlo methods, Math/CS

36 Monte Carlo in action def countDoubles( N ): """ inputs a # of dice rolls outputs the # of doubles """ if N == 0: return 0 # zero rolls, zero doubles… else: d1 = choice( [1,2,3,4,5,6] ) d2 = choice( range(1,7) ) if d1 != d2: return countDoubles( N-1 ) # don't count it else: return 1+countDoubles( N-1 ) # COUNT IT! one roll where is the doubles check? the input N is the total number of rolls How many doubles will you get in N rolls of 2 dice?

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

38 Monte Carlo Monty Hall Suppose you always switch to the other door... What are the chances that you will win the car ? Run it (randomly) 300 times and see!

39 Monte Carlo Monty Hall def MCMH( init, sors, N ): """ plays the "Let's make a deal" game ~ N times returns the number of times you win the car """ if N == 0: return 0 # don't play, can't win carDoor = choice([1,2,3]) # where is the car? if init == carDoor and sors == 'stay': result = 'Car!' elif init == carDoor and sors == 'switch': result = 'Spam.' elif init != carDoor and sors == 'switch': result = 'Car!' else: result = 'Spam.' print 'You get the', result if result == 'Car!': return 1 + MCMH( init, sors, N-1 ) else: return 0 + MCMH( init, sors, N-1 ) Your initial choice! 'switch' or 'stay' number of times to play

40 An example closer to home... 20212223401918170 An overworked CGU student ( S ) leaves Wolfe's after their “late-night” breakfast and, each moment, randomly stumbles toward ACB (South) or toward the dorms (North) ACBDorms (N) (S) Wolfe's Write a program to model and analyze! this scenario... S Once the student arrives at the dorm or classroom, the trip is complete. The program should then print the total number of steps taken. hw2pr3 rs()rwPos(s, nsteps)rwSteps(s, low, hi) take a random step of +1 or -1 take nsteps random steps starting at s take random steps starting at s until you reach either low or hi

41 Homework #2 hw2pr1 – Webserver! hw2pr2 – Monty Hall... hw2pr3 – The sleepwalking student hw2pr4 – Online Monty Hall Choose any two of these...

42 IS 313: Information Technology HTML HyperText Markup Language and the beautiful Tower of Pisa

43 IS 313: Information Technology HTML

44 IS 313: Information Technology CSS

45 HTML CGI AJAX Javascript CSS HyperText Markup Language Cascading Style Sheets body { background-color:#d0e4fe; } h1 { color:orange; text-align:center; } p { font-family:"Times New Roman"; font-size:20px; } Others! IS 313: Information Technology Start here: http://w3schools.com/css/default.asp

46 Web resources ~ on the Web www.w3schools.com started by every technology - and acronym - you'd ever want to know… Tim Berners-Lee

47 (1) Get Apache running on your machine (2) Start from the example "application" to create your own webpage with some text & an image create at least two CSS formats for the same page! Your own webserver... Next time: uploading to a publicly available server submit? Two screenshots....

48 Enjoy your own webhosting! Perhaps you can charge yourself for the service!? Lab hour...

49 Recursion -- not just numbers Relationships Self-similarity elsewhere... Natural phenomena Names -- acronyms What is an “ancestor” ? The TTP Project how much here is leaf vs. stem?


Download ppt "IS 313 Tomorrow… IS 313 last week ? 9/20/09 - today: beyond recursion! 9/27/09 - next wk: web technologies, pt 2 Assignment reminders... Which door to."

Similar presentations


Ads by Google