Lecture 5: Dynamic Data - HMC Computer Science

Download Report

Transcript Lecture 5: Dynamic Data - HMC Computer Science

Computing to the max
You know this would make me
hungry… if it weren't 7 pm!
The not-so-subtle art of singling out the
best (and worst) of anything…
Computing with language
Consider literature a bunch of strings ?
Battle-tested ciphers - and how to break them !
a comparison comparison
> or <
Seasons by Mike Maguire
'm&ms'
'coffee'
[ 0, 42 ]
[ 4, 2 ]
True
'True'
Drawn Inward
Fall leaves when leaves fall.
I'm a head!
What's ahead?
10/14 Dynamic data - references
10/15 ASCII art due
10/21 no class - Fall break
10/22 encipher/decipher due
10/28 Objects and naming 1
10/29 Wandering and Life due
11/4 Objects and naming 2
11/5 Markov text due
11/5 Project proposals due
John Conway
Conway gives a whole new
outlook on "loopy" !
Recursive max
def max( L ):
if len(L) < 2:
return L[0]
If there is only 1 element, it's the max!
elif L[0] < L[1]:
return max( L[1:] )
If the first element is less than the
second, "forget about" the first one and
find the max of everything else…
else:
return max( L[0:1] + L[2:] )
But if the second element is
smaller, forget about it and take
the max of everything else !
A recipe for life ?
and python already has it for us!
The hard part is knowing what we want to maximize!
Out of the box…
If we want the highest price…
And I thought $100
was overpriced!
max( [475.5, 458.0, 441.3, 470.8, 532.8, 520.9] )
'nov'
'jan'
'mar'
'may'
'jul'
'sep'
What if the months are in there, as well?
max( [
[475.5,'nov'], [458.0,'jan'], [441.3,'mar'],
[470.8,'may'], [532.8,'jul'], [520.9,'sep'] ] )
If we want the final word:
L =
['Harvey', 'Mudd', 'College', 'seeks', 'to', 'educate', 'engineers,',
'scientists', 'and', 'mathematicians', 'well-versed', 'in', 'all', 'of', 'these',
'areas', 'and', 'in', 'the', 'humanities', 'and', 'the', 'social', 'sciences', 'so',
'that', 'they', 'may', 'assume', 'leadership', 'in', 'their', 'fields', 'with', 'a',
'clear', 'understanding', 'of', 'the', 'impact', 'of', 'their', 'work', 'on', 'society']
max(L)
or if we want the initial word… ?
min(L)
"max" word
L = [
"to","be","or","not","to","be","that","is","the","question"
def maxWord( L ):
""" finds the "max" word from L, a list of words
"""
return max(L)
]
"max" word - part 2!
L = [
"to","be","or","not","to","be","that","is","the","question"
]
def maxWord( L ):
""" finds the "max" word from L, a list of words
"""
return max(L) ??
How could we
redefine max!?
This is max?
longest word?
most times?
lowest scrabble
score?
"Best" word ~ longest
L = [
"to","be","or","not","to","be","that","is","the","question"
def bestWord( L ):
""" finds the "best" word from L, a list of words
"""
]
"Best" word ~ lowest scrabble score
def scrabbleScore(w):
# see homework #2!
Let's abbreviate this function as
scsc(w)
def bestWord( L ):
""" finds the "best" word from L, a list of words
here, "best" means lowest scrabble score
"""
Add printing as you see fit!
What are these?
>>> bestNumber( [ 10, 20, 30, 40, 50, 60, 70 ] )
40
>>> bestNumber( [ 100, 200, 300, 400 ] )
100
>>> bestNumber( [ 1, 2, 3, 4, 5, 6, 7, 8, 7 ] )
8
>>> mode( [ 1, 2, 3, 4, 5, 6, 7, 8, 7 ] )
7
Guesses for bestNumber ?
for mode ?
"Coding Challenge"
Nothing but the best!
Write these two functions:
Hint:
abs( x ) is built-in to Python
Use bestWord as a guide
def bestNumber( L ):
""" returns the # in L closest to 42 """
Hint:
You may want to define
a helper function !
def mode( L ):
""" returns the element appearing most often in L """
Try it…
Write this function:
Hint:
abs( x ) is built-in to Python
Use bestWord as a guide
def bestNumber( L ):
""" returns the # in L closest to 42 """
Try it…
Hint:
You may want to define
a helper function !
def mode( L ):
""" returns the element appearing most often in L """
An example “close to home”
Hw5 Pr1
Starbucks
...
CGU
(W)
0
S
...
22 23 24 25 26 27 28
An overworked CGU student (S) leaves Starbucks after
their “late-night” breakfast and, each moment, randomly
stumbles toward campus (W) or toward home (E)
Once the student arrives at home or the 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...
home
(E)
50
Some random info…
import random
for more explanation, try dir(random) or help(random)
random.choice( L )
chooses 1 element from the list L
random.choice( ['drucker', 'sisat', 'sah'] )
How would you get a random int from 0 to 9?
random.uniform(low,hi)
chooses a random float from low to hi
random.uniform(41.9,42.1)
How likely is this to return 42 ?
An example: the ASCII equalizer
How could we write a function to print lines of asterisks… ?
******
******
******
******
******
******
******
******
******
******
******
first ~ all the same
******
**
***********
*
*****
*******
*******
**********
***
****
second ~ random lengths
******
*******
********
*******
******
*****
****
***
****
*****
******
third ~ changing by 1
An example: the ASCII equalizer
Notes…
first ~ all the same
second ~ random lengths
third ~ changing by 1
Randomness vs. Determinism
Are there random numbers?
Can a computer generate them?
RNG
Output
A “black box” model of a
random number generator.
Randomness vs. Determinism
Are there random numbers?
Can a computer generate them?
Yes
Not without help!
The RNG revealed.
Output
http://en.wikipedia.org/wiki/Mersenne_twister
Periodic!
p = 219937-1
True Randomness !
LavaRnd’s lava lamps
using a chaotic physical system to
seed random number generators
(Patent 5,732,138: "Method for seeding a pseudorandom number generator with a cryptographic
hash of a digitization of a chaotic system.")
www.wired.com/wired/archive/11.08/random.html
This has since been “improved”…
The two Monte Carlos
Making random
numbers work
for you!
Monte Carlo casino,
Monaco
Monte Carlo methods, Math/CS
An example “close to home”
Hw5 Pr1
Starbucks
...
CGU
(W)
0
...
S
22 23 24 25 26 27 28
home
(E)
50
An overworked CGU student (S) leaves Starbucks after
their “late-night” breakfast and, each moment, randomly
stumbles toward campus (W) or toward home (E)
Once the student arrives at home or the 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
rwPos(s, nsteps)
take nsteps random
steps starting at s
rwSteps(s, low, hi)
take random steps starting at s until
you reach either low or hi
Gel electrophoresis
one of many applications for random walks…
uses a basic randomwalk model with unequal
step probabilities
Used to separate proteins and
nucleic acids (DNA) from a
biological sample. Molecules
with different properties travel
different distances.
print: Making programs talk to you!
import time
def countdown( num ):
""" remarkably accurate sim.
of 2006's final moments """
if num == 0:
return 'Hooray!'
else:
print 'Countdown is', num
time.sleep(1)
return countdown(num-1)
you can slow things
down, as well!
Essential for debugging …
print: Making programs talk to you!
Debugging had to be discovered. I can remember
the exact instant when I realized that a large part
of my life from then on was going to be spent in
finding mistakes in my own programs.
- Maurice Wilkes
Programming: the art of debugging an empty file.
- The Jargon File
http://www.tuxedo.org/~esr/jargon/
The first bug
Grace Hopper
from the UNIVAC 1
“In the days they used oxen for heavy pulling, when one ox couldn't budge
a log, they didn't try to grow a larger ox. We shouldn't be trying for
bigger and better computers, but for better systems of computers.”
Reference
Changeable types:
vs. Value
Unchangeable types:
tuple
list
string
int
L = [7,11,'hi']
float
bool
x = 42
Reference
,
Pointer,
id
42
L
7
11
L[0]
L[1]
'hi'
L[2]
x
“Pass By Value”
def main()
""" calls conform """
print " Welcome to Conformity, Inc. "
7
fav = 7
conform(fav)
fav
print " My favorite number is", fav
def conform(fav)
""" sets input to 42 """
fav = 42
return fav
fav
“Pass By Value”
def main()
""" calls conform """
print " Welcome to Conformity, Inc. "
7
fav = 7
conform(fav)
fav
print " My favorite number is", fav
PASS
BY
VALUE
def conform(fav)
""" sets input to 42 """
fav = 42
return fav
7 42
fav
“Pass by value” means that data is copied when sent to a method
Passing lists by value…
def main()
""" calls conform2 """
print " Welcome to Conformity, Inc. "
fav = [ 7, 11 ]
conform2(fav)
print " My favorite numbers are", fav
fav
def conform2(fav)
""" sets all of fav to 42 """
fav[0] = 42
fav[1] = 42
7
11
L[0]
L[1]
fav
What gets passed by
value here?
Passing lists by value…
def main()
""" calls conform2 """
print " Welcome to Conformity, Inc. "
fav = [ 7, 11 ]
conform2(fav)
print " My favorite numbers are", fav
fav
def conform2(fav)
""" sets all of fav to 42 """
fav[0] = 42
fav[1] = 42
7
11
L[0]
L[1]
The reference is
copied!
fav
can change data
elsewhere!
The conclusion
You can change the contents of lists in
functions that take those lists as input.
(actually, lists or any mutable objects)
Those changes will be visible everywhere.
(immutable objects are safe, however)
Views of the world
Engineers think their equations approximate reality.
Views of the world
Engineers think their equations approximate reality.
Physicists think reality approximates their equations.
Views of the world
Engineers think their equations approximate reality.
Physicists think reality approximates their equations.
Mathematicians don't care.
Views of the world
Engineers think their equations approximate reality.
Physicists think reality approximates their equations.
Mathematicians don't care.
Creating structure from a
few simple facts...
Axioms
Definitions
Creating structure from a
few simple actions ...
for
arrays
variables
while
arithmetic operations
if/else
Proof
Algorithm
Lists’ flexibility
Lists can hold ANY type of data
A = [ 42., 75., 70. ]
42.0
list
A
they don’t have to
be horizontal lists!
float
75.0
float
70.0
float
Lists’ flexibility
Lists can hold ANY type of data
A = [ 42., 75., 70. ]
42.0
list
A
float
42.0
they don’t have to
be horizontal lists!
list
A
double
75.0
double
70.0
double
75.0
float
70.0
float
Lsits’ flexibility
Lists can hold ANY type of data
42.0
list
A
double
42
list
A
int
“go”
list
A
String
75.0
double
7
int
70.0
double
-11
int
“red”
String
String
2d lists or arrays
Lists can hold ANY type of data -- including lists !
A = [ [1,2,3,4], [5,6], [7,8,9,10,11] ]
list
A
2d arrays
Lists can hold ANY type of data -- including lists !
A = [ [1,2,3,4], [5,6], [7,8,9,10,11] ]
list
A
list
A[0]
list
A[1]
list
A[2]
Jagged arrays
Lists can hold ANY type of data -- including lists !
A = [ [1,2,3,4], [5,6], [7,8,9,10,11] ]
list
A
list
A[0]
list
A[1]
list
A[2]
Rows within 2d arrays need not be the same length…
We will not use jagged arrays
at least in hw 10
Lists can hold ANY type of data -- including lists !
A = [ [1,2,3,4], [5,6], [7,8,9,10,11] ]
list
A
list
A[0]
list
A[1]
list
A[2]
Rows within 2d arrays need not be the same length…
Rectangular arrays
list
A
list
A[0]
A[1][2] = 42
A[0][0]
list
A[1]
list
A[2]
A[2][3]
What does each component of A[1][2] mean ?
How many rows does A have, in general ?
How many columns does A have, in general ?
Creating a 2d array
def create2dArray( width, height ):
""" does just that """
A = []
# start with nothing
for row in range( height ):
for col in range( width ):
return A
Displaying a 2d array
from csgrid import *
B = create2dArray( 10, 10 )
show( B )
B[1][8] = 1
# set this item to 1
csplot.show( B )
nearby coordinates…
Problem 2 -- “Life”
Grid World
John Conway
red cells are alive
Evolutionary rules
• Everything depends on a cell’s
eight neighbors
• Exactly 3 neighbors give birth
to a new, live cell!
• Exactly 2 or 3 neighbors keep an
existing cell alive
• Any other number of neighbors kill
the central cell (or keep it dead)
white cells are empty
Problem 2 -- Life
Grid World
red cells are alive
Evolutionary rules
• Everything depends on a cell’s
eight neighbors
• Exactly 3 neighbors give birth
to a new, live cell!
• Exactly 2 or 3 neighbors keep an
existing cell alive
• Any other number of neighbors kill
the central cell (or keep it dead)
white cells are empty
Problem 2 -- Life
Grid World
red cells are alive
Evolutionary rules
• Everything depends on a cell’s
eight neighbors
• Exactly 3 neighbors give birth
to a new, live cell!
• Exactly 2 or 3 neighbors keep an
existing cell alive
• Any other number of neighbors kill
the central cell (or keep it dead)
white cells are empty
Problem 2 -- Life
Grid World
red cells are alive
Evolutionary rules
• Everything depends on a cell’s
eight neighbors
• Exactly 3 neighbors give birth
to a new, live cell!
• Exactly 2 or 3 neighbors keep an
existing cell alive
• Any other number of neighbors kill
the central cell (or keep it dead)
white cells are empty
Keep going!
life out there...
Problem 2 -- Creating Life
B = createNextLifeBoard( B )
new generation or "board"
old generation or "board"
0
1
2
3
4
0
5
0
0
1
1
2
2
3
3
4
4
5
5
1
2
3
4
5
Problem 2 -- Creating Life
B = update( B )
new generation or "board"
old generation or "board"
0
1
2
3
4
0
5
0
0
1
1
2
2
3
3
4
4
5
5
1
2
3
4
5
Problem 2 -- Details
B = update( B )
old generation or "board"
new generation or "board"
For each generation…
• 0 represents an empty cell
• 1 represents a living cell
• outermost edge should
always be left empty (even
if there are 3 neighbors)
• compute all cells based on
their previous neighbors
before updating any of them
http://www.math.com/students/wonders/life/life.html
life out there...
Problem 2 -- to  and beyond!
• Are there stable life configurations?
"rocks"
• Are there oscillating life configurations?
"plants"
period 3
period 2
• Are there self-propagating life configurations?
"animals"
Problem 2 -- to  and beyond!
• Are there life configurations that expand forever?
• What is the largest amount of the life
universe that can be filled with cells?
• Are all feasible configurations reachable?
• How sophisticated can the structures
in the life universe be?
Google for GOLLY, Game of Life
Lab & Homework…
Without extra spaces…
import sys
for i in range(4):
for j in range(8):
sys.stdout.write('#')
print
method (function) that
prints only its input
software object representing the
screen's standard output
########
########
########
########
Output
Files
Want to analyze one of your papers?
f becomes the "file object" representing
paper.txt in this case.
f = open('paper.txt')
You will first need to save your file as "plain
text" or else all the special formatting
characters will still be in there!
text = f.read()
text is now one BIG string
words = text.split()
words is now one BIG list of words (strings)
max(words)
min(words)
or anything else you might
want to investigate… !
Two households, both alike in dignity,
In fair Verona, where we lay our scene,
From ancient grudge break to new mutiny,
Where civil blood makes civil hands unclean.