660 likes | 939 Views
IST 380. Welcome… but be sure to watch your head! . IST 380 last hw ?. Homework #1: Functions & recursion!. Homework #2. hw2pr1 – Monty Hall. Fun ctions in Python. hw2pr2 – The sleepwalking student. Random walks. hw2pr3 – Python integration. List comprehensions.
E N D
IST 380 Welcome… but be sure to watch your head! IST 380 last hw?
Homework #1: Functions & recursion! Homework #2 hw2pr1 – Monty Hall... Functions in Python hw2pr2 – The sleepwalking student Random walks... hw2pr3 – Python integration List comprehensions
Recursive design… fun! easy!? (1) Program the base case. (2) Find the self-similarity. cool! (3) Do one step! indexing and slicing (4) Delegate the rest to recursion… Aha!
One step? …is easy to do with Python s = 'aliens' s[0] How do we get at the initial character of s? s[ ] How do we get at ALL THE REST of s? L = [ 42, 21 ] L[0] How do we get at the initial element of L? L[ ] How do we get at ALL the REST of L?
Recursive design #1 'cs5' defmylen(s): """ input: any string, s output: the number of characters in s """ if: else: base case test! Ask yourself: "How could I use the length of anything smaller than s?" Then do!
defmylen(s): """ input: any string, s output: the number of characters in s """ ifs =='': return0 else: return1 + mylen(s[1:]) There's not much len left here!
[1,4,3,42, 7,-100] Design #2 defmymax(L): """ input: a NONEMPTY list, L output: L's maximum element """ if: elif: else: len(L)==1 base case test! another case…
Design #2 defmymax(L): """ input: a NONEMPTY list, L output: L's maximum element """ iflen(L) == 1: returnL[0] elif L[0] < L[1]: returnmymax( L[1:] ) else: returnmymax( L[0:1] + L[2:] ) Hey - do I get a slice?!
power(2,5) == 32.0 Try it! sajak('wheel of fortune') == 6 5 4 2 2* 2 == What about y? You decide… def power(b,p): defsajak(s): """ returns b to the p power Use recursion, not ** Inputs: int b, int p: the base and the power """ """ returns the number of vowels in the input string, s """ if s == '': Base case test p == 0 if : Base case test return Let's try these two together…! return elif return else: else: return return Want more power? Handle negative values of p, too. What 7-letter English word wmaximizes sajak(w) ? Want more Pat? For example,power(5,-1) == 0.2
def power(b,p): """ inputs: base b and power p (an int) implements: b**p """ if p == 0: return elifp < 0: return ____________________ else: return Recursion is power!
Looking behind the curtain… http://www.pythontutor.com/visualize.html
# of vowels in s sajak(s): D E S I G N When there are no letters, there are ZERO vowels Base case? Rec. step? Look at the initial character. if s[0] is NOT a vowel, the answer is sajak( s[1:] ) if s[0] is a vowel, the answer is 1 + sajak( s[1:] )
def sajak(s): if s == '': return 0 elif s[0]=='a' or s[0]=='e' or… Base Case Checking for a vowel: Try #1
I guess Python's the in thing Python is… in >>> 'i'in'team' False >>> 'cs'in'physics' True >>> 'i'in'alien' True >>> 3*'i'in'alien' False >>> 42 in [41,42,43] True >>> 42 in[[42], '42'] False
if s[0] IS a vowel, the answer is 1 + the # of vowels in the rest of s defsajak(s): iflen(s) == 0: return 0 elif s[0] in'aeiou': return else: return Base Case Recursive Cases if s[0] is NOT a vowel, the answer is just the number of vowels in the rest of s
if s[0] IS a vowel, the answer is 1 + the # of vowels in the rest of s defsajak(s): iflen(s) == 0: return 0 elif s[0] in'aeiou': return1 + sajak(s[1:]) else: return sajak(s[1:]) Base Case Recursive Cases if s[0] is NOT a vowel, the answer is just the number of vowels in the rest of s
sajak( 'eerier' ) A good description for recursion!
functional programming >>> 'fun'in'functional' True • representation via list structures (data) • leverage self-similarity (recursion) • create small building blocks (functions) Composed together-- to solve/investigate problems. Functional programming conceptually concise efficient for the computer… vs. functional procedural or sequential
A random aside… import random allows use of dir(random) and help(random) from random import * all random functions are now available! uniform(low,hi) chooses a random float from low to hi floats have 16 places of precision Here, 14 of them are after the decimal point choice( L ) chooses 1 element from the sequence L choice( 'pitzer') choice( ['pitzer', 'cgu', 'scripps'] ) How would you get a random int from 0 to 99 inclusive?
A randomfunction… from random import * def guess( hidden ): """ tries to guess our "hidden" # """ compguess = choice( range(100) ) ifcompguess == hidden: # at last! print 'I got it!' else: guess( hidden ) Suspicious? I am! print the guesses ? slow down… return the number of guesses ? investigate expected # of guesses?!??
Recursive guess-counting code will help for hw2pr1+2 from random import * importtime def guess( hidden ): """ guessing game """ compguess = choice( range(100) ) # print 'I choose', compguess # time.sleep(0.05) ifcompguess == hidden: # at last! # print 'I got it!' return 1 else: return 1 + guess( hidden )
An example closer to home hw2pr2 H/S West Dorm ... ... S Shan (E) (W) 0 22 23 24 25 26 27 28 50 An overworked Claremont student (S) leaves Starbucks after their "late-night" breakfast and, each step, randomly stumbles toward class (W) or toward home (E) Once the student arrives at the dorm or classroom, the trip is complete. The program should then print the total number of steps taken. Write a program to model and analyze! this scenario... rwpos(s,nsteps) rwsteps(s,low,hi) take nsteps random steps starting at s take random steps starting at s until you reach either low or hi
An example closer to home hw2pr2 H/S West Dorm ... ... S Shan (E) (W) 0 22 23 24 25 26 27 28 50 An overworked Claremont student (S) leaves Starbucks after their "late-night" breakfast and, each step, randomly stumbles toward class (W) or toward home (E) How could we create this as an "ASCII" animation? Once the student arrives at the dorm or classroom, the trip is complete. The program should then print the total number of steps taken. Write a program to model and analyze! this scenario... rwpos(s,nsteps) rwsteps(s,low,hi) take nsteps random steps starting at s take random steps starting at s until you reach either low or hi
The two Monte Carlos and their denizens… Insights via random trials Monte Carlo methods, Math/CS Monte Carlo casino, Monaco
The two Monte Carlos and their denizens… Ulam, Stan Ulam Stanislaw Ulam (Los Alamos badge) Insights via random trials Monte Carlo methods, Math/CS Bond, James Bond Monte Carlo casino, Monaco
Monte Carlo in action How many doubles will you get in N rolls of 2 dice? defcountDoubles( N, dialog ): """ input: N, the # of dice rolls dialog: whether to be chatty… output: the # of doubles seen """ if N == 0: return 0 # BASE CASE! if dialog == False: d1 = random.choice( range(1,7) ) d2 = random.choice( range(1,7) ) let's write this together!
Monte Carlo in action How many doubles will you get in N rolls of 2 dice? defcountDoubles( N, dialog ): """ input: N, the # of dice rolls dialog: whether to be chatty… output: the # of doubles seen """ if N == 0: return 0 # BASE CASE! if dialog == False: d1 = random.choice( range(1,7) ) d2 = random.choice( range(1,7) ) else: user = raw_input("Are you ready to roll ") # more conversation here… also d1 and d2, as above if d1 == d2: return 1 + countDoubles( N-1 ) else: return 0 + countDoubles( N-1 ) let's write this together!
Another Monty… ? We've seen Monte Carlo… inspiring the “Monty Hall paradox”
Let's make a deal… '63-'86 Monty inspiring the Monty Hall paradox
Monte Carlo Monty Hall Suppose you always switch to the other door... What are the chances that you will win the prize ? Run it (randomly) 300 times and see!
Monte Carlo Monty Hall 'switch'or'stay' code will help for hw2pr1 Your initial choice! number of times to play def MCMH( init, sors, N ): """ plays the "Let's make a deal" game N times returns the number of times you win the *Spam!* """ if N == 0: return 0 # don't play, can't win przDoor = choice([1,2,3]) # where is the spam (prize) if init == przDoor and sors == 'stay': result = 'Spam!' elif init == przDoor and sors == 'switch': result = 'pmfp.' elif init != przDoor and sors == 'switch': result = 'Spam!' else: result = 'pmfp.' print 'You get the', result if result == 'Spam!': return 1 + MCMH( init, sors, N-1 ) else: return 0 + MCMH( init, sors, N-1 )
5 3 4 7 1 42 6 8 0 9 A B C D E F G H
5 3 4 7 1 42 6 8 0 9 A B C D E F G H
IST 380: now recursing… Or re-cursing, depending on your feelings about recursion! We're computationally complete! What's next? function applications List Comprehensions
Data [13,14,15] Functions sum( ) Snacks The 3 building blocks of CS!
sum range defsum(L): """ input: L, a list of #s output: L's sum """ iflen(L) == 0: return 0.0 else: return L[0] + sum(L[1:]) Base Case Recursive Case
sumrange step? what's cookin' here? defrange(low,hi ): """ input: intslow and hi output: int list from low to hi """ iflow >= hi: return [] else: return excluding hi
sum and range I've seen sum of this before... ? >>> sum(range(1,101))
1784 sum and range >>> sum(range(1,101)) 5050 Looks sort of scruffy for a 7-year old… ! and 100 more… http://www.americanscientist.org/template/AssetDetail/assetid/50686
Data [8,9,10] Functions sq( ) [64,81,100] …together
Map defdbl(x): return 2*x >>>map(dbl, [0,1,2,3,4,5]) [0, 2, 4, 6, 8, 10] defsq(x): return x**2 >>> map(sq, range(6)) [0, 1, 4, 9, 16, 25] >>>map(is_a, 'go away!') [0, 0, 0, 1, 0, 1, 0, 0] defis_a(x): returnx == 'a' What does mapdo? Hey… these look a bit False to me!
Map defdbl(x): return 2*x >>>map(dbl, [0,1,2,3,4,5]) [0, 2, 4, 6, 8, 10] defsq(x): return x**2 >>> map(sq, range(6)) [0, 1, 4, 9, 16, 25] Now I have 0 to complain about! >>>map(is_a, 'go away!') [0, 0, 0, 1, 0, 1, 0, 0] defis_a(x): returnint(x=='a') (1) mapalways returns a list (2) map(f,L)calls fon each item in L
Map, managed! input >>> [ 2*x for x in [0,1,2,3,4,5] ] [0, 2, 4, 6, 8, 10] Looks natural to me! output Python has a "more natural" syntax for map…
Syntax ?! a (frustrated!) rendering of an unfamiliar math problem
Syntax ~ is CS's key resource! a (frustrated!) rendering of an unfamiliar math problem which might have been something like this
Syntax ~ is CS's key resource! a (frustrated!) rendering of an unfamiliar math problem or even this…
List Comprehensions A better map input >>> [ 2*x for x in [0,1,2,3,4,5] ] [0, 2, 4, 6, 8, 10] output What's the syntax saying here?