41fe8f631b1ae9f92b1c17e0dffec012.ppt
- Количество слайдов: 49
IS 313 Tomorrow… 9/20/09 - today: beyond recursion! 9/27/09 - next wk: web technologies, pt 2 Which door to choose? Assignment reminders. . . This week. . . Next week. . . IS 313 last week ?
Computation's Dual Identity "variables as containers" 41 42 name: x type: int LOC: 300 name: y type: int LOC: 304 memory location 300 Computation memory location 304 Data Storage accessed through functions… lists and strings…
Data: review… Suppose s = 'latin' How could we get the first element of s? How could we get the rest of s? (all but the first) What if we then add 'ay' ?
Look good to me! Functions: review… # my own function! def dbl( x ): """ returns double its input, x """ return 2*x keywords Some of Python's baggage… def starts the function return stops it immediately and sends back the return value Comments They begin with # Docstrings They become part of python's built-in help system! With each function be sure to include one that (1) describes overall what the function does, and (2) explains what the inputs mean/are
Functioning with strings and lists… # how do you like your coffee? def undo(s): """ this "undoes" its string input, s """ return 'de' + s >>> undo('caf')) # what does this do? def warp(L): >>> warp('space') """ L can be any sequence """ return L[1: ] + L[0: 1] >>> warp('drake')
Functioning with strings and lists… def chop(s): """ mystery! """ return >>> chop('graduate') 'grad' >>> chop('abcd')) 'a' def stackup(s): """ mystery! """ return >>> stackup('star') 'starrats' >>> stackup('dumbmob ') 'dumbmob bombmud'
Functioning with strings and lists… # you don't need these comments def chop(s): """ this returns half its string input, s """ return s[: len(s)/2] 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('abcd')) 'a' >>> stackup('star') 'starrats' >>> stackup('dumbmob ') 'dumbmob bombmud'
Recursion warning: Be sure to watch your head!
beyond recursion? Creating general functions that will be useful everywhere (or almost…) building blocks with which to compose…
sum recursively def sum(L): """ input: a list of numbers, L output: L's sum """ Base Case if the input list if len(L) == 0: has no elements, its sum is zero return 0. 0 else: return L[0] + sum(L[1: ]) Recursive Case if L does have an element, add that element's value to the sum of the REST of the list…
sum with loops! def sum(L): """ input: a list of numbers, L output: L's sum Starter value """ zero, in this case result_so_far = 0. 0 for e in L: Loop! add e each time! result_so_far = result_so_far + e return result_so_far That's it! Like loops? Check out http: //docs. python. org/tutorial/controlflow. html
Recursion vs. loops? The choice is yours! more loops next week. .
range, recursively what's cookin' here? def range(low, hi): """ input: two ints, low and hi output: list from low up to hi excluding hi """ if hi <= low: return [] else: return [low] +
range, with loops! def range(low, hi): """ input: two ints, low and hi output: list from low up to hi excluding hi """ Starter value result = [] empty list, in this case e = low what's cookin' here? while e < hi: result = result + [e] Loop! add [e] each time! return result Like loops? Check out http: //docs. python. org/tutorial/controlflow. html
sum and range >>> sum(range(1, 101)) Looks sort of scruffy for a 7 -year old… !
Is this really the best name Guido Van Rossum could think of? List Comprehensions
List Comprehensions A Loop in a List! input >>> [ 2*x for x in [0, 1, 2, 3, 4, 5] ] [0, 2, 4, 6, 8, 10] output What is going on here? and the "running" variable can have any name. . .
List Comprehensions A Loop in a List! input >>> [ 2*x for x in [0, 1, 2, 3, 4, 5] ] (1) x takes on each value in the list or string (2) The operation 2*x happens for each x [0, 2, 4, 6, 8, 10] output and the "running" variable can have any name. . .
List Comprehensions A Loop in a List! input output >>> [ _______ for y in range(6) ] [0, 1, 4, 9, 16, 25] >>> [ _____ for c in 'igotit' ] [True, False, True, False]
List Comprehensions Anything you want to happen to each element of a list name that takes on the value of each element in turn the list (or string) input output >>> [ 2*x for x in [0, 1, 2, 3, 4, 5] ] [0, 2, 4, 6, 8, 10] Is this really the best name Guido Van Rossum could think of? >>> [ y**2 for y in range(6) ] [0, 1, 4, 9, 16, 25] any name is OK! input output >>> [ c == 'a' for c in 'go away!' ] [0, 0, 0, 1, 0, 0]
List Comprehensions Anything you want to happen to each element of a list name that takes on the value of each element in turn Lazy lists the list (or string) input output >>> [ 2*x for x in [0, 1, 2, 3, 4, 5] ] Makes sense to me! [0, 2, 4, 6, 8, 10] One-hit wonders >>> [ y**2 for y in range(6) ] [0, 1, 4, 9, 16, 25] Google'sc. Maps == 'a' for in 'go >>> [ c [0, 0, 0, 1, 0, 0] away!' ]
A list comprehension by any other name would be as sweet… Raw recursion. . . length of the list L def len(L): if L == []: return 0 else: return 1 + len(L[: ]) count of 'A's in the string s def count. As(s): if len(s) == 0: return 0 elif s[0] == 'A': return 1 + count. As(s[1: ]) else: return count. As(s[1: ]) 7 lines! Aargh!
. . . vs. List Comprehensions def len(L): LC = [ ______ for x in L] return sum( LC ) def count. As(s): suppose s is a string of capital letters LC = [ ____ for c in s] return sum( LC ) I prefer one-liners!
vs. List Comprehensions # of vowels def sajak(s): LC = [ return sum( LC ) for c in s] Remember True == 1 and False == 0 # of odd elements def num. Odds(L): LC = [ return sum( LC ) for x in L]
Try it! Write def count(e, L): Write each of these functions concisely using list comprehensions… input: e, any element L, any list or string output: the # of times L contains e example: count('f', 'fluff') == 3 LC = [ return sum(LC) Write def lotto(Y, W): Extra! def numdivs(N): Remember True == 1 and False == 0 for x in L ] don't use e in here somehow… here! input: Y and W, two lists of lottery numbers (ints) W are the winning numbers Y are your numbers output: the # of matches between Y & W example: lotto([5, 7, 42, 44], [3, 5, 7, 44]) == 3 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 primes. Upto( P ):
Quiz 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 Write def count(e, L): LC = [ return sum(LC) for x in L ] don't use e in here somehow… here!
Write input: Y and W, two lists of lottery numbers (ints) output: the # of matches between Y & W W are the winning numbers Y are your numbers example: lotto([5, 7, 42, 44], [3, 5, 7, 44]) == 3 def lotto(Y, W):
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) What if you want the divisors themselves? or prime #s? def primes. Upto( P ): How could you use this to compute all of the prime numbers up to P?
Maya Lin, Architect…
Maya Lin, Computer Scientist… "two-by-four landscape"
Maya Lin, Computer Scientist… One building block, carefully applied, over 50, 000 times…
A random aside… import random from random import * allows use of dir(random) and help(random) choice( L ) chooses 1 element from the sequence L all random functions are now available! choice( ['rock', 'paper', 'scissors'] ) How would you get a random int from 0 to 9 inclusive? uniform(low, hi) uniform(41. 9, 42. 1) How likely is this to return 42 ? chooses a random float from low to hi
A random function… from random import * def guess( hidden ): """ guesses the user's hidden # """ compguess = choice( range(100) ) if compguess == hidden: print 'I got it!' else: guess( hidden ) # at last! This is a bit suspicious… print the guesses ? slow down… return the number of guesses ?
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 )
The two Monte Carlos Making random numbers work for you! Monte Carlo methods, Math/CS Monte Carlo casino, Monaco
Monte Carlo in action How many doubles will you get in N rolls of 2 dice? the input N is the total number of rolls def count. Doubles( N ): """ inputs a # of dice rolls outputs the # of doubles """ if N == 0: return 0 # zero rolls, zero doubles… else: d 1 = choice( [1, 2, 3, 4, 5, 6] ) one roll d 2 = choice( range(1, 7) ) if d 1 != d 2: return count. Doubles( N-1 ) # don't count it else: return 1+count. Doubles( N-1 ) # COUNT IT! where is the doubles check?
Monty Hall Let’s make a deal ’ 63 -’ 86 Sept. 1990 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 car ? Run it (randomly) 300 times and see!
Monte Carlo Monty Hall Your initial choice! 'switch' or 'stay' 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 car """ if N == 0: return 0 # don't play, can't win car. Door = choice([1, 2, 3]) # where is the car? if init == car. Door and sors == 'stay': elif init == car. Door and sors == 'switch': elif init != car. Door and sors == 'switch': else: result = = 'Car!' 'Spam. ' print 'You get the', result if result == 'Car!': else: return 1 + MCMH( init, sors, N-1 ) return 0 + MCMH( init, sors, N-1 )
An example closer to home Wolfe's . . . ACB (S) 0 hw 2 pr 3 . . . S 17 18 19 20 21 22 23 Dorms (N) 40 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) 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. . . rs() take a random step of +1 or -1 rw. Pos(s, nsteps) take nsteps random steps starting at s rw. Steps(s, low, hi) take random steps starting at s until you reach either low or hi
Homework #2 hw 2 pr 1 – Webserver! Choose any two of these. . . hw 2 pr 2 – Monty Hall. . . hw 2 pr 3 – The sleepwalking student hw 2 pr 4 – Online Monty Hall
IS 313: Information Technology HTML Hyper. Text Markup Language <b>and the beautiful</b> <i>Tower of Pisa</i>
IS 313: Information Technology HTML
IS 313: Information Technology CSS
IS 313: Information Technology HTML CSS Hyper. Text Markup Language Cascading Style Sheets body { background-color: #d 0 e 4 fe; } h 1 { color: orange; text-align: center; } p { font-family: "Times New Roman"; font-size: 20 px; } Start here: http: //w 3 schools. com/css/default. asp Others! CGI Javascript AJAX
Web resources ~ on the Web www. w 3 schools. com every technology and acronym - you'd ever want to know… started by Tim Berners-Lee
Your own webserver. . . (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! • submit? Two screenshots. . Next time: uploading to a publicly available server
Enjoy your own webhosting! Perhaps you can charge yourself for the service!? Lab hour. . .
Recursion -- not just numbers Self-similarity elsewhere. . . Relationships What is an “ancestor” ? Names -- acronyms The TTP Project Natural phenomena how much here is leaf vs. stem?
41fe8f631b1ae9f92b1c17e0dffec012.ppt