Date post: | 11-Jan-2016 |
Category: |
Documents |
Upload: | evan-kelly |
View: | 214 times |
Download: | 0 times |
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...
Computation's Dual Identity
name: xtype: intLOC: 300
41
"variables as containers"
memory location 300
Computation Data Storage
name: ytype: intLOC: 304
42
memory location 304
accessed through functions…lists and strings…
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' ?
# 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 functionreturn stops it
immediately and sends back the return value
Some of Python's baggage…
Look good to me!
Functions: review…
# 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')
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'
# 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'
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…
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 Caseif 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…
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 valuezero, in this case
Loop!add e each time!
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?
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] +
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 hiStarter
valueempty list, in this case
Loop!add [e] each
time!
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… !
List Comprehensions
Is this really the best name Guido Van Rossum
could think of?
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...
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
List Comprehensions
>>> [ _______ for y in range(6) ]
[0, 1, 4, 9, 16, 25]
>>> [ __________ for c in 'igotit' ]
[True, False, False, False, True, False]output
output
input
input
A Loop in a List!
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
output
output
input
input
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!
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
output
output
input
input
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
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
... vs. List Comprehensions
LC = [ ______ for x in L] return sum( LC )
len(L):
countAs(s):LC = [ ________ for c in s] return sum( LC )
def
def
I prefer one-liners!
suppose s is a string of capital letters
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
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 stringoutput: 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 numbersW are the winning numbers
Remember True == 1 and False == 0
Extra! def numdivs(N):
input: N, an int >= 2output: the number of positive divisors of Nexample: 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 ):
Quiz
Write
def count(e,L):
input: e, any element L, any list or stringoutput: 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…
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 numbersW are the winning numbers
Extra!
def numdivs(N):
input: N, an int >= 2output: the number of positive divisors of Nexample: 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?
Maya Lin, Architect…
"two-by-four landscape"
Maya Lin, Computer Scientist…
One building block, carefully applied, over 50,000 times…
Maya Lin, Computer Scientist…
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!
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…
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
Monte Carlo casino, Monaco
Making random numbers work for you!
Monte Carlo methods, Math/CS
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?
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
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
An example closer to home
......20 21 22 23 401918170
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)
ACB Dorms(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
Homework #2
hw2pr1 – Webserver!
hw2pr2 – Monty Hall...
hw2pr3 – The sleepwalking student
hw2pr4 – Online Monty Hall
Choose any two of these...
IS 313: Information Technology
HTML HyperText Markup Language
<b>and the beautiful</b> <br>
<i>Tower of Pisa</i>
IS 313: Information Technology
HTML
IS 313: Information Technology
CSS
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
Web resources ~ on the Web
www.w3schools.com
started by
every technology - and acronym - you'd ever want to know…
Tim Berners-Lee
(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....
Enjoy your own webhosting! Perhaps you can
charge yourself for the service!?
Lab hour...
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?