Computing to the max - HMC Computer Science

advertisement
This would make me hungry…
but I ate breakfast this morning!
Computing to the max
The not-so-subtle art of singling out
the best (and worst) of anything…
Last hw?
N-step sleepwalking?
Turtle graphics??
a comparison comparison
'm&ms'
'coffee'
[ 0, 42 ]
[ 4, 2 ]
Artistic renderings!!!
This week!
Hw #3 due next Sunday…
True
'True'
> or <
pr0: Are we The Matrix?
pr1: Lab…
pr2: Sorting + Caesar!
Computing with language
• What's in a Writ1 paper, anyway?
• Battle-tested ciphers & how to break them…
Partner Submissions…
… only two + only if it's both's!
This would make me hungry…
but I ate breakfast this morning!
Computing to the max
The not-so-subtle art of singling out
the best (and worst) of anything…
Last hw?
N-step sleepwalking?
Turtle graphics??
a comparison comparison
'm&ms'
'coffee'
[ 0, 42 ]
[ 4, 2 ]
Artistic renderings!!!
This week!
Hw #3 due next Sunday…
True
'True'
> or <
pr0: Are we The Matrix?
pr1: Lab…
pr2: Sorting + Caesar!
Computing with language
• What's in a Writ1 paper, anyway?
• Battle-tested ciphers & how to break them…
Partner Submissions…
… only two + only if it's both's!
?
?
max
A recipe for life ?
and python already has it for us…
to the max
And I thought $50
was overpriced!
NASDAQ: GOOG
Want the highest price?
max( [475.5, 458.0, 441.3, 470.8, 532.8, 520.9] )
'nov'
'jan'
'mar'
'may'
'jul'
ST
'sep'
What if the months are in there, as well?
max( [ [470.8,'may'], [532.8,'jul'], [520.9,'sep'] ] )
STm
max( [ ['may',470.8], ['jul',532.8], ['sep',520.9] ] )
mST
to the max
And I thought $50
was overpriced!
NASDAQ: GOOG
Want the highest price?
max( [475.5, 458.0, 441.3, 470.8, 532.8, 520.9] )
'nov'
'jan'
'mar'
'may'
'jul'
ST
'sep'
What if the months are in there, as well?
max( [ [470.8,'may'], [532.8,'jul'], [520.9,'sep'] ] )
STm
max( [ ['may',470.8], ['jul',532.8], ['sep',520.9] ] )
mST
Mudd's max?
MSt
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']
Or Mudd's min?
max(L)
min(L)
general-purpose
max
[ 7, 10, -2, 41, -46, 42, 15 ]
def max( L ):
""" returns the max element from L
input: L, a nonempty list
"""
if len(L) < 2:
# one element is the max.
return L[0]
Spacey!
I like it!
elif
L[0]
<
return max( L[1:] )
L[1] : #1 wins
else:
return max( L[0:1] + L[2:] )
#0 wins
scrabble-score
max
['Harvey', 'Mudd', 'College', 'seeks', 'to', 'educate', … ]
def bestWord( L ):
""" returns L's max-scrabble-score word
input: L, a list of strings (words)
"""
if len(L) < 2:
# one element is the max
return L[0]
elif
L[0] <
L[1] : #1 wins
return bestWord( L[1:] )
else:
#0 wins
return bestWord( L[0:1] + L[2:] )
scrabble-score
max
['Harvey', 'Mudd', 'College', 'seeks', 'to', 'educate', … ]
def bestWord( L ):
""" returns L's max-scrabble-score word
input: L, a list of strings (words)
"""
if len(L) < 2:
# one element is the max
return L[0]
elif sScore(L[0]) < sScore(L[1]): #1 wins
return bestWord( L[1:] )
else:
#0 wins
return bestWord( L[0:1] + L[2:] )
What else might be nice to know ?
A more comprehensive solution
L = ['Harvey','Mudd','College','seeks','to',…]
def bestWord( L ):
""" returns L's max-scrabble-score word
"""
This
does
LoL = [ [sScore(w), w] for w in L ]
look
funny!
bestpair = max( LoL )
return bestpair[1]
A more comprehensive solution
I loathe
hazy
code!
L = [ 'aliens', 'zap', 'hazy', 'code' ]
def bestWord( L ):
""" returns L's max-scrabble-score word
"""
LoL = [ [sScore(w), w] for w in L ]
LoL =
[ [6,'aliens'], [14,'zap'], [19,'hazy'], [7,'code'] ]
bestpair = max( LoL )
bestpair =
[19,'hazy']
return bestpair[1]
'hazy'
Other examples…
What is bestnumb ?
What is mostnumb ?
>>> bestnumb( [10,20,30,40,50,60,70] )
40
>>> bestnumb( [100,200,300,400] )
100
>>> bestnumb( [1,2,3,4,5,6,7,8,7] )
8
>>> mostnumb( [1,2,3,4,5,6,7,8,7] )
7
These functions have
made me number
Try it!
L = [ 'aliens', 'zap', 'hazy', 'code' ]
def beststr(L):
LoL = [ [len(s),s] for s in L ]
1. What is LoL?
here is a start: LoL is [ [6,'aliens'],
2. What is bst?
bst = max( LoL )
return bst[1]
3. What is returned?
L = [ 30, 40, 50 ]
Extra!
Change exactly three
characters in this code
so that 3 is returned.
Use the LoL method to write these two functions
def bestnumb(L):
""" returns the # in L closest to 42 """
LoL = [
bst =
return bst[1]
]
Hint: Python has abs(x) built-in
L = [ 3,4,5,7,6,7 ]
def mostnumb( L ):
Hint: Define a helper function!
""" returns the item most often in L """
LoL = [
bst =
return bst[1]
]
def count(e,L):
""" count e's in L """
Quiz
L = [ 'aliens', 'zap', 'hazy', 'code' ]
def beststr(L):
LoL = [ [len(s),s] for s in L ]
1. What is LoL?
[ [6,'aliens'], [3,'zap'], [4,'hazy'], [4,'code'] ]
2. What is bst?
bst = max( LoL )
return bst[1]
3. What is returned?
Extra!
[6,'aliens']
'aliens'
Change exactly three
characters in this code
so that 3 is returned.
L = [ 30, 40, 50 ]
def bestnumb(L):
""" returns the # in L closest to 42 """
LoL = [ [abs(x-42),x] for x in L ]
bst = min( LoL )
return bst[1]
Hint: Python has abs(x) built-in
L = [ 3,4,5,7,6,7 ]
def mostnumb( L ):
""" returns the item most often in L """
LoL = [ [count(e,L),e] for e in L ]
bst = max( LoL )
return bst[1]
Hint: Define a helper function!
def count(e,L):
LC = [e==x for x in L]
return sum(LC)
L = [ 'aliens', 'zap', 'hazy', 'code' ]
def beststr(L):
LoL = [ [len(s),s] for s in L ]
1. What is LoL?
[ [6,'aliens'], [3,'zap'], [4,'hazy'], [4,'code'] ]
bst = max( LoL )
2. What is bst?
[6,'aliens']
return bst[1]
3. What is returned?
Extra!
'aliens'
Change exactly three characters in this code so that 3 is returned.
[ 30, 40, 50 ]
Example
def bestnumb( L ):
""" returns the # closest to 42 in L """
LoL = [ [abs(x-42),x] for x in L ]
bst = min( LoL )
[30,40,50]
L
[[12,30],[2,40],[8,50]]
LoL
return bst[1]
[2,40]
40
bst
bst[1]
Helper function: count(e,L)
Example
def count( e, L ):
""" returns the # of e's in L """
LC = [ e==x for x in L ]
return sum( LC )
L
LoL
[6,7,7,8]
[ [1,6], [2,7], [2,7], [1,8] ]
bst
[2,7]
[6,7,7,8]
7
def mostnumb( L ):
""" returns the item most often in L """
LoL = [ [count(e,L),e] for e in L ]
bst = max( LoL )
return bst[1]
Could you use x here
instead of e?
hw3pr1: big data?
Any guesses as to what kind of data this is?
I find your lack of faith in
this data disturbing.
hw3pr1: sound data!
what are the vertical and
horizontal axes here?
Sound
physics
sampling
samples taken every
1/22050th of a second
(or some sampling rate)
air pressure
continuous variation of
air pressure vs. time
time
quantization
Each sample is measured on a
loudness scale from -32,768 to
32,767. (This fits into 2 bytes.)
storage
These two bytes are called a frame. Raw audio
data - such as what is written to the surface of
a CD - is simply a list of these frames.
pulse code modulation = PCM data
Computing with language
ideas / meaning
language / words / phrases
strings
numbers / bits
Python strings
are here.
Computing with language
open
questions
in AI …
ideas / meaning
overlap of CS + ROW!
language / words / phrases
This week…
processing language –
how English-y is it?
strings
how strings are
represented and stored
numbers / bits
Next week…
Caesar Cipher: encipher
encipher(s,n)
'I <3 Latin'
encipher( 'I <3 Latin' , 0 )
returns
encipher( 'I <3 Latin' , 1 )
returns
encipher( 'I <3 Latin' , 2 )
returns
encipher( 'I <3 Latin' , 3 )
returns
'L <3 Odwlq'
encipher( 'I <3 Latin' , 4 )
returns
'M <3 Pexmr'
encipher( 'I <3 Latin' , 5 )
returns
'N <3 Qfyns'
encipher( 'I <3 Latin' , 25 )
returns
'J <3 Mbujo'
'K <3 Ncvkp'
'H <3 Kzshm'
Caesar Cipher: encipher
encipher(s,n)
should return the string s with each
alphabetic character shifted/wrapped
by n places in the alphabet
'I <3 Latin'
encipher( 'I <3 Latin' , 0 )
returns
encipher( 'I <3 Latin' , 1 )
returns
encipher( 'I <3 Latin' , 2 )
returns
encipher( 'I <3 Latin' , 3 )
returns
'L <3 Odwlq'
encipher( 'I <3 Latin' , 4 )
returns
'M <3 Pexmr'
encipher( 'I <3 Latin' , 5 )
returns
'N <3 Qfyns'
encipher( 'I <3 Latin' , 25 )
returns
'J <3 Mbujo'
'K <3 Ncvkp'
'H <3 Kzshm'
ASCII
American Standard Code for Information Interchange
1 byte
8 bits
The SAME bits represent an integer or a
string, depending on type: int or str
ASCII
American Standard Code for Information Interchange
over in memory…
value:
'/'
type: str
name:
1 byte
The types
determine how to
interpret the bits;
the names don't
matter at all…
8 bits
Identical bits are
stored in each
variable!
value:
47
type: int
The SAME bits represent an integer or a
string, depending on type: int or str
name:
ASCII
convert # to char
chr
ord
convert char to #
This is why
'College' <
'areas' !
Julius spr'15
chr and ord
ASCII
values
abcdefghijklmnopqrstuvwxyz
97
99
101
103
107
109
111
113
115
117
119
122
ABCDEFGHIJKLMNOPQRSTUVWXYZ
65
67
69
71
73
75
77
79
81
83
85
87
90
ord value
ord value
ord( c )
Input: a string of one character, c
Output: an integer, the ASCII value of c
chr( n )
Input: an integer in range(255)
Output: a one-char. string of that ASCII value
Conversion
functions
105
[ [i,chr(i)] for i in range(128) ]
Ex1
[ ord(i) for i in '**** CS! ****' ]
Ex2
Try these!
chr, ord,
and rot13
What is ord('U')/2?
What is chr( ord('i')+13 )?
What is chr( ord('W')+13 )?
Finish rot13 to "shift" a letter, c, by 13 spots…
def rot13( c ):
""" rotate c by 13 chars, "wrapping" as needed; NON-LETTERS don't change """
if 'a' <= c <= 'z':
# test if c is a lowercase letter
new_ord = ord(c) + 13
# if so, find the # 13 spots ahead
if new_ord <= ord('z'):
# check if it's in bounds!
return chr(new_ord)
# if so, return it
else:
# otherwise
return
# what to return?
elif
# what test should go here?
# what would go here, if we had room?
else:
# what should be done in the else?
How would this change if we wanted to rotate by n spots?
Rot 13
def rot13( c ):
""" rotates c by 13 chars, "wrapping" as needed
NON-LETTERS don't change!
"""
if 'a' <= c <= 'z':
new_ord = ord(c) + 13
if new_ord <= ord('z'):
return chr(new_ord)
else:
return chr(
)
elif 'A' <= c <= 'Z':
# upper-case test!
else:
Rotate n? Rotate an entire string?
Caesar Cipher: decipher
Caesar
Brutus
>>> decipher('Bzdrzq bhogdq? H oqdedq Bzdrzq rzkzc.')
'Caesar cipher? I prefer Caesar salad.'
S1
S2
>>> decipher('Hu lkbjhapvu pz doha ylthpuz hmaly dl mvynla '\
'lclyfaopun dl ohcl slhyulk.')
'An education is what remains after we forget everything we
have learned.'
>>> decipher('Uifz xpsl ju pvu xjui b qfodjm!')
PL
LAT
>>> decipher('gv vw dtwvg')
But how ?
Decipher?
Strategies?
Algorithms?
gv
hw
ix
jy
kz
All possible la
decipherings mb
nc
od
pe
qf
rg
sh
ti
uj
vk
wl
xm
yn
zo
ap
bq
cr
ds
et
fu
Decipher?
Strategies?
Algorithms?
vw
wx
xy
yz
za
ab
bc
cd
de
ef
fg
gh
hi
ij
jk
kl
lm
mn
no
op
pq
qr
rs
st
tu
uv
dtwvg
euxwh
fvyxi
gwzyj
hxazk
iybal
jzcbm
kadcn
lbedo
mcfep
ndgfq
oehgr
pfihs
qgjit
rhkju
silkv
tjmlw
uknmx
vlony
wmpoz
xnqpa
yorqb
zpsrc
aqtsd
brute
csvuf
gv
hw
ix
jy
kz
All possible la
decipherings mb
nc
od
pe
qf
rg
sh
ti
uj
vk
wl
xm
yn
zo
ap
bq
cr
ds
et
fu
Decipher?
Strategies?
Algorithms?
vw
wx
xy
yz
za
ab
bc
cd
de
ef
fg
gh
hi
ij
jk
kl
lm
mn
no
op
pq
qr
rs
st
tu
uv
dtwvg
euxwh
fvyxi
gwzyj
hxazk
iybal
jzcbm
kadcn
lbedo
mcfep
ndgfq
oehgr
pfihs
qgjit
rhkju
silkv
tjmlw
uknmx
vlony
wmpoz
xnqpa
yorqb
zpsrc
aqtsd
brute
csvuf
[0,
[2,
[2,
[0,
[2,
[4,
[0,
[1,
Score [4,
them [3,
all [0,
[2,
[2,
[3,
[2,
[1,
[0,
[1,
[2,
[3,
[2,
[1,
[0,
[1,
[4,
[3,
'gv
'hw
'ix
'jy
'kz
'la
'mb
'nc
'od
'pe
'qf
'rg
'sh
'ti
'uj
'vk
'wl
'xm
'yn
'zo
'ap
'bq
'cr
'ds
'et
'fu
vw
wx
xy
yz
za
ab
bc
cd
de
ef
fg
gh
hi
ij
jk
kl
lm
mn
no
op
pq
qr
rs
st
tu
uv
dtwvg'],
euxwh'],
fvyxi'],
gwzyj'],
hxazk'],
iybal'],
jzcbm'],
kadcn'],
lbedo'],
mcfep'],
ndgfq'],
oehgr'],
pfihs'],
qgjit'],
rhkju'],
silkv'],
tjmlw'],
uknmx'],
vlony'],
wmpoz'],
xnqpa'],
yorqb'],
zpsrc'],
aqtsd'],
brute'],
csvuf']
gv
hw
ix
jy
kz
All possible la
decipherings mb
nc
od
pe
qf
rg
sh
ti
uj
vk
wl
xm
yn
zo
ap
bq
cr
ds
et
fu
Decipher?
Strategies?
Algorithms?
vw
wx
xy
yz
za
ab
bc
cd
de
ef
fg
gh
hi
ij
jk
kl
lm
mn
no
op
pq
qr
rs
st
tu
uv
dtwvg
euxwh
fvyxi
gwzyj
hxazk
iybal
jzcbm
kadcn
lbedo
mcfep
ndgfq
oehgr
pfihs
qgjit
rhkju
silkv
tjmlw
uknmx
vlony
wmpoz
xnqpa
yorqb
zpsrc
aqtsd
brute
csvuf
[0,
[2,
[2,
[0,
[2,
max! [4,
[0,
[1,
Score [4,
them [3,
all [0,
[2,
[2,
[3,
[2,
[1,
[0,
[1,
[2,
[3,
[2,
[1,
[0,
[1,
[4,
[3,
'gv
'hw
'ix
'jy
'kz
'la
'mb
'nc
'od
'pe
'qf
'rg
'sh
'ti
'uj
'vk
'wl
'xm
'yn
'zo
'ap
'bq
'cr
'ds
'et
'fu
vw
wx
xy
yz
za
ab
bc
cd
de
ef
fg
gh
hi
ij
jk
kl
lm
mn
no
op
pq
qr
rs
st
tu
uv
dtwvg'],
euxwh'],
fvyxi'],
gwzyj'],
hxazk'],
iybal'],
jzcbm'],
kadcn'],
lbedo'],
mcfep'],
ndgfq'],
oehgr'],
pfihs'],
qgjit'],
rhkju'],
silkv'],
tjmlw'],
uknmx'],
vlony'],
wmpoz'],
xnqpa'],
yorqb'],
zpsrc'],
aqtsd'],
brute'],
csvuf']
Measuring Englishness
Very English-y
"Call me Ishmael."
"Attack at dawn!"
"rainbow, table, candle"
higher scores
"Yow! Legally-imposed CULTURE-reduction
is CABBAGE-BRAINED!"
"quadruplicity drinks procrastination"
"Hold the newsreader's nose squarely, waiter, or
friendly milk will countermand my trousers."
"the gostak distims the doshes"
"hension, framble, bardle"
"jufict, stofwus, lictpub"
"itehbs, rsnevtr, khbsota"
lower scores
"epadxo, nojarpn, gdxokpw"
"h o q dedqBzdrzqrzkzc"
Not English-y
All of these sound
good to me!
gv
hw
ix
jy
kz
All possible la
decipherings mb
nc
od
pe
qf
rg
sh
ti
uj
vk
wl
xm
yn
zo
ap
bq
cr
ds
et
fu
Decipher?
Strategies?
Algorithms?
vw
wx
xy
yz
za
ab
bc
cd
de
ef
fg
gh
hi
ij
jk
kl
lm
mn
no
op
pq
qr
rs
st
tu
uv
dtwvg
euxwh
fvyxi
gwzyj
hxazk
iybal
jzcbm
kadcn
lbedo
mcfep
ndgfq
oehgr
pfihs
qgjit
rhkju
silkv
tjmlw
uknmx
vlony
wmpoz
xnqpa
yorqb
zpsrc
aqtsd
brute
csvuf
[0,
[2,
[2,
[0,
[2,
max! [4,
[0,
[1,
Score [4,
them [3,
all [0,
[2,
[2,
[3,
[2,
[1,
[0,
[1,
[2,
[3,
[2,
[1,
[0,
[1,
[4,
[3,
'gv
'hw
'ix
'jy
'kz
'la
'mb
'nc
'od
'pe
'qf
'rg
'sh
'ti
'uj
'vk
'wl
'xm
'yn
'zo
'ap
'bq
'cr
'ds
'et
'fu
vw
wx
xy
yz
za
ab
bc
cd
de
ef
fg
gh
hi
ij
jk
kl
lm
mn
no
op
pq
qr
rs
st
tu
uv
dtwvg'],
euxwh'],
fvyxi'],
gwzyj'],
hxazk'],
iybal'],
jzcbm'],
kadcn'],
lbedo'],
mcfep'],
ndgfq'],
oehgr'],
pfihs'],
qgjit'],
rhkju'],
silkv'],
tjmlw'],
uknmx'],
vlony'],
wmpoz'],
xnqpa'],
yorqb'],
zpsrc'],
aqtsd'],
brute'],
csvuf']
gv
hw
ix
jy
kz
All possible la
decipherings mb
nc
od
pe
qf
rg
sh
ti
uj
vk
wl
xm
yn
zo
ap
bq
cr
ds
et
fu
Decipher?
Strategies?
Algorithms?
vw
wx
xy
yz
za
ab
bc
cd
de
ef
fg
gh
hi
ij
jk
kl
lm
mn
no
op
pq
qr
rs
st
tu
uv
dtwvg
euxwh
fvyxi
gwzyj
hxazk
iybal
jzcbm
kadcn
lbedo
mcfep
ndgfq
oehgr
pfihs
qgjit
rhkju
silkv
tjmlw
uknmx
vlony
wmpoz
xnqpa
yorqb
zpsrc
aqtsd
brute
csvuf
S
c
o
r
e
s
max!
[6.9e-05,
[3.6e-05,
[1.4e-07,
[8.8e-11,
[7.2e-10,
[0.01503,
[3.7e-08,
[0.00524,
[0.29041,
[0.00874,
[7.3e-07,
[0.06410,
[0.11955,
[3.1e-06,
[1.1e-08,
[2.6e-05,
[0.00012,
[3.1e-06,
[0.02011,
[1.5e-06,
[1.9e-07,
[5.7e-08,
[0.00024,
[0.02060,
[0.45555,
[0.00011,
'gv
'hw
'ix
'jy
'kz
'la
'mb
'nc
'od
'pe
'qf
'rg
'sh
'ti
'uj
'vk
'wl
'xm
'yn
'zo
'ap
'bq
'cr
'ds
'et
'fu
vw
wx
xy
yz
za
ab
bc
cd
de
ef
fg
gh
hi
ij
jk
kl
lm
mn
no
op
pq
qr
rs
st
tu
uv
dtwvg'],
euxwh'],
fvyxi'],
gwzyj'],
hxazk'],
iybal'],
jzcbm'],
kadcn'],
lbedo'],
mcfep'],
ndgfq'],
oehgr'],
pfihs'],
qgjit'],
rhkju'],
silkv'],
tjmlw'],
uknmx'],
vlony'],
wmpoz'],
xnqpa'],
yorqb'],
zpsrc'],
aqtsd'],
brute'],
csvuf']
HRS 338 Snczx
Algorithms
Englishness...
Classifying life
Removing/Sorting
and Jotto!
HW 3
some perspective on
all of this
"algorithm" stuff…
Edward Frenkel
Gesundheit!
Algorithms
?
Englishness...
Classifying life
Removing/Sorting
and Jotto!
HW 3
Hw #3 due Monday
"Office" hrs: Mon. 2-4pm
Weekend tutoring? yes!
Edward Frenkel
BR 5 Snczx
Algorithms
!
Englishness...
Classifying life
Removing/Sorting
and Jotto!
HW 3
Hw #3 due Monday
"Office" hrs: Mon. 2-4pm
Weekend tutoring? yes!
Edward Frenkel
Gesundheit!
Design…
remAll(e,L)
remove all e's from L
Top-down
design
Visualize
Split into parts
Build each part
Combine
Test
Design…
remAll(e,L)
remove all e's from L
Top-down
design
remAll(42,[5,7,42,8,42])
Visualize
[5,7,8]
Split into parts
Build each part
Combine
remAll('q','qaqqlqqiqqiiqeqqnqs')
Test
'aliiiens'
Design…
remAll(e,L)
remove all e's from L
Top-down
design
it
remAll(42,[5,7,42,8,42])
Visualize
[5,7,8]
Split into parts
Build each part
Combine
it
remAll('q','qaqqlqqiqqiiqeqqnqs')
Test
'aliiiens'
Design…
remAll(e,L)
remove all e's from L
Top-down
design
it if L[0] != e
remAll(42,[5,7,42,8,42])
Visualize
keep L[0]
+ remove e from the rest
[5,7,8]
Split into parts
Build each part
Combine
Test
it
remAll('q','qaqqlqqiqqiiqeqqnqs')
drop L[0]
+ remove e from the rest
'aliiiens'
if L[0] == e
Design…
remAll(e,L)
remove all e's from L
Top-down
design
it if L[0] != e
remAll(42,[5,7,42,8,42])
Visualize
keep L[0]
+ remove e from the rest
[5,7,8]
Split into parts
Build each part
Combine
Test
it
- or -
remAll('q','qaqqlqqiqqiiqeqqnqs')
drop L[0]
+ remove e from the rest
'aliiiens'
if L[0] == e
Allie Russell, '12
Design…
remAll(e,L)
remove all e's from L
Top-down
design
Visualize
def remAll( e, L ):
Split into parts
if len(L) == 0:
L empty
Build each part
elif L[0] != e:
L[0] wasn't e
Combine
Test
else:
L[0] was e
Design…
remAll(e,L)
remove all e's from L
Top-down
design
Visualize
Split into parts
Build each part
def remAll( e, L ):
if len(L) == 0:
return L
elif L[0] != e:
return L[0:1] + remAll(e,L[1:])
Combine
else:
return remAll(e,L[1:])
Test
Teal… !
remAll(e,L)
remove all e's from L
Top-down
design
Visualize
Split into parts
Build each part
def remAll( e, L ):
if len(L) == 0:
return L
elif L[0] != e:
return L[0:1] + remAll(e,L[1:])
Combine
else:
return remAll(e,L[1:])
Test
Teal… !
remAll(e,L)
remove all e's from L
Top-down
design
Visualize
Split into parts
Build each part
def remAll( e, L ):
if len(L) == 0:
return L
elif L[0] != e:
return L[0:1] + remAll(e,L[1:])
Combine
else:
return remAll(e,L[1:])
Test
Design…
but design of what?
Code?
syntax
Algorithms!
ideas!
Variations…
remAll(8, [7,8,9,8])
[7,9]
remAll
remOne(8, [7,8,9,8])
[7,9,8]
remOne
remUpto(8,[7,8,9,8])
[9,8]
remUpto
remAll('d', 'coded')
'coe'
remAll
remOne('d', 'coded')
'coed'
remOne
remUpto('d','coded')
'ed'
remUpto
Subsequences
def subseq( s, sbig )
s is the subsequence
to find (or not)
subseq('', 'cataga')
True or False?
sbig is the bigger string in
which we are looking for s
T or F?
subseq('ctg', 'cataga')
subseq('ctg', 'tacggta')
subseq('aliens', 'always frighten dragons')
subseq('trogdor', 'that dragon is gone for good')
Here there be
NO dragons!
Why do these succeed? Or fail?
Try it!
1
Algorithm design
def remAll( e, L ):
""" removes all e's from L """
if len(L) == 0:
return L
elif L[0] != e:
return L[0:1] + remAll(e,L[1:])
else:
return remAll(e,L[1:])
Change remAll so that it
removes only one e from L.
(We could call it remOne.)
remOne(8,[7,8,9,8])
[7,9,8]
2
Make changes to remAll so
that it removes elements upto
and including the first e in L.
(We could call it remUpto.)
remUpto('d','coded')
def subseq( s, sbig ):
""" returns True if s is a subseq. of sbig,
False otherwise. Both are strings.
"""
if s == '':
return True
if
'ed'
3
Write the other
cases needed for
subseq…
from remAll to remOne
def remAll( e, L ):
""" returns seq. L with all e's rmovd
"""
if len(L) == 0:
return L
elif L[0] != e:
return L[0:1] + remAll( e, L[1:] )
else:
return
remOne(8,[7,8,9,8])
remAll( e, L[1:] )
[7,9,8]
remOne('d','coded')
'coed'
from remOne to remUpto
def remOne( e, L ):
""" returns seq. L with one e rmovd
"""
if len(L) == 0:
return L
elif L[0] != e:
return L[0:1] + remOne( e, L[1:] )
else:
return
remUpto(8,[7,8,9,8])
L[1:]
[9,8]
remUpto('d','coded')
'ed'
Subseq ~ sketching it out…
subseq( s, sbig )
subseq('ctg', 'tacggta')
What is a small (initial) piece of the problem?
How would we describe it in terms of the inputs?
- or -
What is left after handling this piece?
Are there other functions we will need?
Subseq ~ trying (coding) it out…
def subseq( s, sbig ):
""" returns True if s is a subseq. of sbig;
False otherwise. Both are strings.
"""
if s == '': return True
Base
case(s)
Recursive
step(s)
Subseq ~ trying (coding) it out…
def subseq( s, sbig ):
""" returns True if s is a subseq. of sbig;
False otherwise. Both are strings.
"""
if s == '': return True
Base case(s)
Recursive
step(s)
Let's try it in Sublime directly…
Subseq ~ trying (coding) it out…
def subseq( s, sbig ):
""" returns True if s is a subseq. of sbig;
False otherwise. Both are strings.
"""
if s == '':
return True
Base case(s)
elif s[0] not in sbig:
return False
it
else:
sbigrest = remUpto( s[0], sbig )
return subseq( s[1:], sbigrest )
Recursive
step(s)
Where are the useit and loseit here?
Subseq ~ trying it out…
def subseq( s, sbig ):
""" returns True if s is a subseq. of sbig;
False otherwise. Both are strings.
"""
if s == '':
return True
Base case(s)
elif s[0] not in sbig:
return False
it
else:
sbigrest = remUpto( s[0], sbig )
return subseq( s[1:], sbigrest )
Recursive
step(s)
hw3pr2: LCS
Longest Common Subsequence
'HUMAN'
'CGCTGAGCTAGGCA...'
'CHIMPANZEE'
'ATCCTAGGTAACTG...'
+109more
Eye oneder if this haz
other aplications?
design of what?
Code?
Algorithms!
Why?
Screenshot from the ClustalX multiple subsequence alignment tool...
Subsequences
(Jotto)
(Sorting)
Hey!?
Trinocular
aliens
?
What was gained
(or lost) here?
Phylogeny
Subsequences @ HMC
host: figs
Jane
parasites: wasps
together:
Jane's Challenge: 6 continents, 100s of species…
Complete!
also in hw3pr2: Jotto !
a word-guessing game…
robot
otter
These are
two cute
Let's try it!
What will each of these jottoscoring examples return?
jotto('geese',
jotto('fluff',
jotto('pears',
jotto('xylyl',
Getting started...
'seems')
'lulls')
'diner')
'slyly')
Extra! Which of these 8 is the
cruellest hidden jotto word?
jotto(s1,s2)
sort( L )
LCS(s1,s2)
should return the jotto score
for any strings s1 and s2
should return a new list that is
the sorted version of the input L
should return the longest common
subsequence of strings s1 and s2
sort( [7,42,5] )
LCS( 'ctg', 'tagc' )
(see above for examples)
don't need
to write
any code
for these
(yet...)
[5,7,42]
but think
about how
you'd
approach
them
'tg'
Brainstorm algorithms for these problems -- what helper functions might help each one?
What will each of these jottoscoring examples return?
jotto('geese',
jotto('fluff',
jotto('pears',
jotto('xylyl',
'seems')
'lulls')
'diner')
'slyly')
Getting started...
3
2
2
4
Extra! Which of these 8 is the
cruellest hidden jotto word?
jotto(s1,s2)
sort( L )
LCS(s1,s2)
should return the jotto score
for any strings s1 and s2
should return a new list that is
the sorted version of the input L
should return the longest common
subsequence of strings s1 and s2
don't need
to write
any code
for these
(yet...)
but think
about how
you'd
approach
them
Brainstorm algorithms for these problems -- what helper functions might help each one?
decipher( 'Weet bksa ed xecumeha 3!' )
decipher( 'Weet bksa ed xecumeha 3!' )
and have a great weekend, too ... !
Download