Computing to the max Last hw? The not-so-subtle art of singling out - - PowerPoint PPT Presentation

computing to the max last hw
SMART_READER_LITE
LIVE PREVIEW

Computing to the max Last hw? The not-so-subtle art of singling out - - PowerPoint PPT Presentation

This would make me hungry but I ate breakfast this morning! Computing to the max Last hw? The not-so-subtle art of singling out N-step sleepwalking? the best (and worst) of anything Turtle graphics?? Artistic renderings!!! a comparison


slide-1
SLIDE 1

The not-so-subtle art of singling out the best (and worst) of anything…

Computing to the max

'm&ms' [ 0, 42 ] a comparison comparison [ 4, 2 ] True 'True' 'coffee' > or <

  • Battle-tested ciphers & how to break them…

Computing with language

  • What's in a Writ1 paper, anyway?

This week!

Hw #3 due next Sunday…

Last hw?

Turtle graphics?? Artistic renderings!!! N-step sleepwalking?

This would make me hungry… but I ate breakfast this morning!

Partner Submissions…

… only two + only if it's both's!

pr0: Are we The Matrix? pr1: Lab… pr2: Sorting + Caesar!

slide-2
SLIDE 2

The not-so-subtle art of singling out the best (and worst) of anything…

Computing to the max

'm&ms' [ 0, 42 ] a comparison comparison [ 4, 2 ] True 'True' 'coffee' > or <

  • Battle-tested ciphers & how to break them…

Computing with language

  • What's in a Writ1 paper, anyway?

This week!

Hw #3 due next Sunday…

Last hw?

Turtle graphics?? Artistic renderings!!! N-step sleepwalking?

This would make me hungry… but I ate breakfast this morning!

Partner Submissions…

… only two + only if it's both's!

pr0: Are we The Matrix? pr1: Lab… pr2: Sorting + Caesar!

slide-3
SLIDE 3

?

slide-4
SLIDE 4

?

slide-5
SLIDE 5

max

A recipe for life ?

and python already has it for us…

slide-6
SLIDE 6

to the max

Want the highest price? What if the months are in there, as well?

max( [475.5, 458.0, 441.3, 470.8, 532.8, 520.9] )

'sep' 'jul' 'may' 'mar' 'jan' 'nov'

max( [ [470.8,'may'], [532.8,'jul'], [520.9,'sep'] ] )

And I thought $50 was overpriced!

NASDAQ: GOOG

max( [ ['may',470.8], ['jul',532.8], ['sep',520.9] ] )

ST STm mST

slide-7
SLIDE 7

to the max

Want the highest price? What if the months are in there, as well? Mudd's max? Or Mudd's min?

max( [475.5, 458.0, 441.3, 470.8, 532.8, 520.9] )

'sep' 'jul' 'may' 'mar' 'jan' 'nov'

max( [ [470.8,'may'], [532.8,'jul'], [520.9,'sep'] ] )

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']

min(L)

max( [ ['may',470.8], ['jul',532.8], ['sep',520.9] ] )

max(L)

ST STm mST MSt

And I thought $50 was overpriced!

NASDAQ: GOOG

slide-8
SLIDE 8

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] elif L[0] < L[1] : #1 wins return max( L[1:] ) else: #0 wins return max( L[0:1] + L[2:] )

Spacey! I like it!

general-purpose max

[ 7, 10, -2, 41, -46, 42, 15 ]

slide-9
SLIDE 9

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', … ]

slide-10
SLIDE 10

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:] )

scrabble-score max

['Harvey', 'Mudd', 'College', 'seeks', 'to', 'educate', … ] What else might be nice to know ?

slide-11
SLIDE 11

A more comprehensive solution

def bestWord( L ): """ returns L's max-scrabble-score word """ LoL = [ [sScore(w), w] for w in L ] bestpair = max( LoL ) return bestpair[1]

This does look funny!

L = ['Harvey','Mudd','College','seeks','to',…]

slide-12
SLIDE 12

A more comprehensive solution

def bestWord( L ): """ returns L's max-scrabble-score word """ LoL = [ [sScore(w), w] for w in L ] bestpair = max( LoL ) return bestpair[1]

I loathe hazy code!

L = [ 'aliens', 'zap', 'hazy', 'code' ]

LoL = [ [6,'aliens'], [14,'zap'], [19,'hazy'], [7,'code'] ] bestpair = [19,'hazy']

'hazy'

slide-13
SLIDE 13

Other examples…

>>> 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

What is bestnumb ? What is mostnumb ?

These functions have made me number
slide-14
SLIDE 14

L = [ 3,4,5,7,6,7 ]

def beststr(L): LoL = [ [len(s),s] for s in L ] bst = max( LoL ) return bst[1]

Try it!

def bestnumb(L):

""" returns the # in L closest to 42 """

LoL = [ ] bst = return bst[1] def mostnumb( L ):

""" returns the item most often in L """

LoL = [ ] bst = return bst[1]

Hint: Define a helper function! Hint: Python has abs(x) built-in

L = [ 'aliens', 'zap', 'hazy', 'code' ]

  • 1. What is LoL?
  • 2. What is bst?
  • 3. What is returned?

Use the LoL method to write these two functions def count(e,L): """ count e's in L """

L = [ 30, 40, 50 ]

Extra!

Change exactly three characters in this code so that 3 is returned.

here is a start: LoL is [ [6,'aliens'],

slide-15
SLIDE 15

def beststr(L): LoL = [ [len(s),s] for s in L ] bst = max( LoL ) return bst[1]

Quiz

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] 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! Hint: Python has abs(x) built-in

L = [ 'aliens', 'zap', 'hazy', 'code' ]

  • 1. What is LoL?
  • 2. What is bst?
  • 3. What is returned?

def count(e,L): LC = [e==x for x in L] return sum(LC) Extra!

Change exactly three characters in this code so that 3 is returned.

L = [ 3,4,5,7,6,7 ] L = [ 30, 40, 50 ]

[ [6,'aliens'], [3,'zap'], [4,'hazy'], [4,'code'] ] [6,'aliens'] 'aliens'

slide-16
SLIDE 16

def beststr(L): LoL = [ [len(s),s] for s in L ] bst = max( LoL ) return bst[1]

Extra! Change exactly three characters in this code so that 3 is returned.

L = [ 'aliens', 'zap', 'hazy', 'code' ]

  • 1. What is LoL?
  • 2. What is bst?
  • 3. What is returned?

[ [6,'aliens'], [3,'zap'], [4,'hazy'], [4,'code'] ] [6,'aliens'] 'aliens'

slide-17
SLIDE 17

def bestnumb( L ):

""" returns the # closest to 42 in L """

LoL = [ [abs(x-42),x] for x in L ] bst = min( LoL ) return bst[1]

Example

[30,40,50]

[[12,30],[2,40],[8,50]]

L [2,40] 40 LoL bst

[ 30, 40, 50 ]

bst[1]

slide-18
SLIDE 18

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]

Example

def count( e, L ):

""" returns the # of e's in L """

LC = [ e==x for x in L ] return sum( LC )

Helper function: count(e,L)

[6,7,7,8]

[ [1,6], [2,7], [2,7], [1,8] ]

L

[2,7] 7

LoL bst

[6,7,7,8]

Could you use x here instead of e?
slide-19
SLIDE 19

hw3pr1: big data?

I find your lack of faith in this data disturbing.

Any guesses as to what kind of data this is?

slide-20
SLIDE 20

hw3pr1: sound data!

what are the vertical and horizontal axes here?

slide-21
SLIDE 21

Sound

continuous variation of air pressure vs. time

samples taken every 1/22050th of a second (or some sampling rate) Each sample is measured on a loudness scale from -32,768 to 32,767. (This fits into 2 bytes.) 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.

sampling quantization storage physics

pulse code modulation = PCM data

time air pressure

slide-22
SLIDE 22

Computing with language

strings language / words / phrases numbers / bits ideas / meaning

Python strings are here.

slide-23
SLIDE 23

how strings are represented and stored

  • pen

questions in AI … processing language – how English-y is it?

Computing with language

strings language / words / phrases numbers / bits ideas / meaning

This week… Next week…

  • verlap of CS + ROW!
slide-24
SLIDE 24

Caesar Cipher: encipher

encipher( 'I <3 Latin' , 0 ) encipher( 'I <3 Latin' , 1 ) encipher( 'I <3 Latin' , 2 ) encipher( 'I <3 Latin' , 3 ) encipher( 'I <3 Latin' , 4 ) encipher( 'I <3 Latin' , 5 ) encipher( 'I <3 Latin' , 25 )

returns returns returns returns returns returns returns

'I <3 Latin' 'J <3 Mbujo' 'K <3 Ncvkp' 'L <3 Odwlq' 'M <3 Pexmr' 'N <3 Qfyns' 'H <3 Kzshm'

encipher(s,n)

slide-25
SLIDE 25

Caesar Cipher: encipher

encipher( 'I <3 Latin' , 0 ) encipher( 'I <3 Latin' , 1 ) encipher( 'I <3 Latin' , 2 ) encipher( 'I <3 Latin' , 3 ) encipher( 'I <3 Latin' , 4 ) encipher( 'I <3 Latin' , 5 ) encipher( 'I <3 Latin' , 25 )

returns returns returns returns returns returns returns

'I <3 Latin' 'J <3 Mbujo' 'K <3 Ncvkp' 'L <3 Odwlq' 'M <3 Pexmr' 'N <3 Qfyns' 'H <3 Kzshm'

encipher(s,n)

should return the string s with each alphabetic character shifted/wrapped by n places in the alphabet

slide-26
SLIDE 26

ASCII

8 bits

The SAME bits represent an integer or a string, depending on type: int or str

American Standard Code for Information Interchange 1 byte

slide-27
SLIDE 27

ASCII

8 bits

The SAME bits represent an integer or a string, depending on type: int or str

American Standard Code for Information Interchange

type: str type: int name: name: value: value:

'/' 47

Identical bits are stored in each variable! The types determine how to interpret the bits; the names don't matter at all…

1 byte

  • ver in memory…
slide-28
SLIDE 28

chr

  • rd

convert char to # convert # to char

ASCII

This is why 'College' < 'areas' !

Julius spr'15
slide-29
SLIDE 29

chr and ord

chr( n )

  • rd( c )

Input: an integer in range(255) Input: a string of one character, c

abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ

ASCII values Output: a one-char. string of that ASCII value Output: an integer, the ASCII value of c Conversion functions

97 122 65 90 99 101 103 105 107 109 111 113 115 117 119 67 69 71 73 75 77 79 81 83 87 85

[ [i,chr(i)] for i in range(128) ] [ ord(i) for i in '**** CS! ****' ]

Try these!

Ex1 Ex2

  • rd value
  • rd value
slide-30
SLIDE 30

chr, ord,

What is ord('U')/2? What is chr( ord('W')+13 )? What is chr( ord('i')+13 )?

and rot13

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? Finish rot13 to "shift" a letter, c, by 13 spots…

How would this change if we wanted to rotate by n spots?
slide-31
SLIDE 31

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?

slide-32
SLIDE 32

Caesar Cipher: decipher

>>> decipher('Bzdrzq bhogdq? H oqdedq Bzdrzq rzkzc.') 'Caesar cipher? I prefer Caesar salad.' >>> 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.'

But how ?

>>> decipher('Uifz xpsl ju pvu xjui b qfodjm!')

>>> decipher('gv vw dtwvg')

Caesar Brutus

S1 S2 PL LAT

slide-33
SLIDE 33

Decipher? Strategies? Algorithms?

slide-34
SLIDE 34

Strategies? Algorithms?

gv vw dtwvg hw wx euxwh ix xy fvyxi jy yz gwzyj kz za hxazk la ab iybal mb bc jzcbm nc cd kadcn

  • d de lbedo

pe ef mcfep qf fg ndgfq rg gh oehgr sh hi pfihs ti ij qgjit uj jk rhkju vk kl silkv wl lm tjmlw xm mn uknmx yn no vlony zo op wmpoz ap pq xnqpa bq qr yorqb cr rs zpsrc ds st aqtsd et tu brute fu uv csvuf

Decipher?

All possible decipherings

slide-35
SLIDE 35

Strategies? Algorithms?

gv vw dtwvg hw wx euxwh ix xy fvyxi jy yz gwzyj kz za hxazk la ab iybal mb bc jzcbm nc cd kadcn

  • d de lbedo

pe ef mcfep qf fg ndgfq rg gh oehgr sh hi pfihs ti ij qgjit uj jk rhkju vk kl silkv wl lm tjmlw xm mn uknmx yn no vlony zo op wmpoz ap pq xnqpa bq qr yorqb cr rs zpsrc ds st aqtsd et tu brute fu uv csvuf

Decipher?

All possible decipherings

[0, 'gv vw dtwvg'], [2, 'hw wx euxwh'], [2, 'ix xy fvyxi'], [0, 'jy yz gwzyj'], [2, 'kz za hxazk'], [4, 'la ab iybal'], [0, 'mb bc jzcbm'], [1, 'nc cd kadcn'], [4, 'od de lbedo'], [3, 'pe ef mcfep'], [0, 'qf fg ndgfq'], [2, 'rg gh oehgr'], [2, 'sh hi pfihs'], [3, 'ti ij qgjit'], [2, 'uj jk rhkju'], [1, 'vk kl silkv'], [0, 'wl lm tjmlw'], [1, 'xm mn uknmx'], [2, 'yn no vlony'], [3, 'zo op wmpoz'], [2, 'ap pq xnqpa'], [1, 'bq qr yorqb'], [0, 'cr rs zpsrc'], [1, 'ds st aqtsd'], [4, 'et tu brute'], [3, 'fu uv csvuf']

Score them all

slide-36
SLIDE 36

Strategies? Algorithms?

gv vw dtwvg hw wx euxwh ix xy fvyxi jy yz gwzyj kz za hxazk la ab iybal mb bc jzcbm nc cd kadcn

  • d de lbedo

pe ef mcfep qf fg ndgfq rg gh oehgr sh hi pfihs ti ij qgjit uj jk rhkju vk kl silkv wl lm tjmlw xm mn uknmx yn no vlony zo op wmpoz ap pq xnqpa bq qr yorqb cr rs zpsrc ds st aqtsd et tu brute fu uv csvuf

Decipher?

All possible decipherings

[0, 'gv vw dtwvg'], [2, 'hw wx euxwh'], [2, 'ix xy fvyxi'], [0, 'jy yz gwzyj'], [2, 'kz za hxazk'], [4, 'la ab iybal'], [0, 'mb bc jzcbm'], [1, 'nc cd kadcn'], [4, 'od de lbedo'], [3, 'pe ef mcfep'], [0, 'qf fg ndgfq'], [2, 'rg gh oehgr'], [2, 'sh hi pfihs'], [3, 'ti ij qgjit'], [2, 'uj jk rhkju'], [1, 'vk kl silkv'], [0, 'wl lm tjmlw'], [1, 'xm mn uknmx'], [2, 'yn no vlony'], [3, 'zo op wmpoz'], [2, 'ap pq xnqpa'], [1, 'bq qr yorqb'], [0, 'cr rs zpsrc'], [1, 'ds st aqtsd'], [4, 'et tu brute'], [3, 'fu uv csvuf']

Score them all max!

slide-37
SLIDE 37

Measuring Englishness

Very English-y Not English-y

"quadruplicity drinks procrastination" "the gostak distims the doshes" "Call me Ishmael." "rainbow, table, candle" "hension, framble, bardle" "jufict, stofwus, lictpub" "epadxo, nojarpn, gdxokpw" "itehbs, rsnevtr, khbsota" "h o q dedqBzdrzqrzkzc"

All of these sound good to me!

"Hold the newsreader's nose squarely, waiter, or friendly milk will countermand my trousers."

"Attack at dawn!"

"Yow! Legally-imposed CULTURE-reduction is CABBAGE-BRAINED!"

higher scores lower scores

slide-38
SLIDE 38

Strategies? Algorithms?

gv vw dtwvg hw wx euxwh ix xy fvyxi jy yz gwzyj kz za hxazk la ab iybal mb bc jzcbm nc cd kadcn

  • d de lbedo

pe ef mcfep qf fg ndgfq rg gh oehgr sh hi pfihs ti ij qgjit uj jk rhkju vk kl silkv wl lm tjmlw xm mn uknmx yn no vlony zo op wmpoz ap pq xnqpa bq qr yorqb cr rs zpsrc ds st aqtsd et tu brute fu uv csvuf

Decipher?

All possible decipherings

[0, 'gv vw dtwvg'], [2, 'hw wx euxwh'], [2, 'ix xy fvyxi'], [0, 'jy yz gwzyj'], [2, 'kz za hxazk'], [4, 'la ab iybal'], [0, 'mb bc jzcbm'], [1, 'nc cd kadcn'], [4, 'od de lbedo'], [3, 'pe ef mcfep'], [0, 'qf fg ndgfq'], [2, 'rg gh oehgr'], [2, 'sh hi pfihs'], [3, 'ti ij qgjit'], [2, 'uj jk rhkju'], [1, 'vk kl silkv'], [0, 'wl lm tjmlw'], [1, 'xm mn uknmx'], [2, 'yn no vlony'], [3, 'zo op wmpoz'], [2, 'ap pq xnqpa'], [1, 'bq qr yorqb'], [0, 'cr rs zpsrc'], [1, 'ds st aqtsd'], [4, 'et tu brute'], [3, 'fu uv csvuf']

Score them all max!

slide-39
SLIDE 39

[6.9e-05, 'gv vw dtwvg'], [3.6e-05, 'hw wx euxwh'], [1.4e-07, 'ix xy fvyxi'], [8.8e-11, 'jy yz gwzyj'], [7.2e-10, 'kz za hxazk'], [0.01503, 'la ab iybal'], [3.7e-08, 'mb bc jzcbm'], [0.00524, 'nc cd kadcn'], [0.29041, 'od de lbedo'], [0.00874, 'pe ef mcfep'], [7.3e-07, 'qf fg ndgfq'], [0.06410, 'rg gh oehgr'], [0.11955, 'sh hi pfihs'], [3.1e-06, 'ti ij qgjit'], [1.1e-08, 'uj jk rhkju'], [2.6e-05, 'vk kl silkv'], [0.00012, 'wl lm tjmlw'], [3.1e-06, 'xm mn uknmx'], [0.02011, 'yn no vlony'], [1.5e-06, 'zo op wmpoz'], [1.9e-07, 'ap pq xnqpa'], [5.7e-08, 'bq qr yorqb'], [0.00024, 'cr rs zpsrc'], [0.02060, 'ds st aqtsd'], [0.45555, 'et tu brute'], [0.00011, 'fu uv csvuf']

Strategies? Algorithms?

gv vw dtwvg hw wx euxwh ix xy fvyxi jy yz gwzyj kz za hxazk la ab iybal mb bc jzcbm nc cd kadcn

  • d de lbedo

pe ef mcfep qf fg ndgfq rg gh oehgr sh hi pfihs ti ij qgjit uj jk rhkju vk kl silkv wl lm tjmlw xm mn uknmx yn no vlony zo op wmpoz ap pq xnqpa bq qr yorqb cr rs zpsrc ds st aqtsd et tu brute fu uv csvuf

Decipher?

All possible decipherings

max!

S c

  • r

e s

slide-40
SLIDE 40

HRS 338 Snczx

Englishness... Classifying life Removing/Sorting and Jotto!

HW 3

Algorithms

Gesundheit!

Edward Frenkel

some perspective on all of this "algorithm" stuff…

slide-41
SLIDE 41

Englishness... Classifying life Removing/Sorting and Jotto!

HW 3

Algorithms

Hw #3 due Monday "Office" hrs: Mon. 2-4pm Weekend tutoring? yes!

Edward Frenkel

?

slide-42
SLIDE 42

BR 5 Snczx

Englishness... Classifying life Removing/Sorting and Jotto!

HW 3

Algorithms

Gesundheit!

Hw #3 due Monday "Office" hrs: Mon. 2-4pm Weekend tutoring? yes!

Edward Frenkel

!

slide-43
SLIDE 43

Top-down design

Design…

Visualize Split into parts Build each part Combine Test

remAll(e,L)

remove all e's from L

slide-44
SLIDE 44

Design…

remAll('q','qaqqlqqiqqiiqeqqnqs')

'aliiiens'

remAll(42,[5,7,42,8,42])

[5,7,8] remAll(e,L)

remove all e's from L

Visualize Split into parts Build each part Combine Test

Top-down design

slide-45
SLIDE 45

Design…

remAll('q','qaqqlqqiqqiiqeqqnqs')

'aliiiens'

Top-down design

Visualize Split into parts Build each part Combine Test

it

remAll(42,[5,7,42,8,42])

[5,7,8] it remAll(e,L)

remove all e's from L

slide-46
SLIDE 46

Design…

remAll(42,[5,7,42,8,42])

[5,7,8] keep L[0]

+ remove e from the rest

drop L[0]

+ remove e from the rest

remAll('q','qaqqlqqiqqiiqeqqnqs')

'aliiiens' remAll(e,L)

remove all e's from L

if L[0] == e if L[0] != e

Top-down design

Visualize Split into parts Combine Test

it it

Build each part

slide-47
SLIDE 47

Design…

remAll(42,[5,7,42,8,42])

[5,7,8] keep L[0]

+ remove e from the rest

drop L[0]

+ remove e from the rest

remAll('q','qaqqlqqiqqiiqeqqnqs')

'aliiiens' remAll(e,L)

remove all e's from L

if L[0] == e if L[0] != e

Top-down design

Visualize Split into parts Combine Test

it it

Build each part

  • or -
slide-48
SLIDE 48

Allie Russell, '12

slide-49
SLIDE 49

Top-down design

Design…

Visualize Combine Test

def remAll( e, L ): if len(L) == 0: elif L[0] != e: else:

L empty L[0] wasn't e

remAll(e,L)

remove all e's from L

L[0] was e

Split into parts Build each part

slide-50
SLIDE 50

Top-down design

Design…

Visualize Test

def remAll( e, 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:])

Split into parts Build each part Combine

remAll(e,L)

remove all e's from L

slide-51
SLIDE 51

Top-down design

Visualize Test

def remAll( e, 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:])

Split into parts Build each part Combine

remAll(e,L)

remove all e's from L

Teal… !

slide-52
SLIDE 52

Top-down design

Visualize Test

def remAll( e, 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:])

Split into parts Build each part Combine

remAll(e,L)

remove all e's from L

Teal… !

slide-53
SLIDE 53

Design…

but design of what?

Code? Algorithms!

syntax ideas!

slide-54
SLIDE 54

remOne

remAll(8, [7,8,9,8]) [7,9] remOne(8, [7,8,9,8]) [7,9,8]

remUpto

remUpto(8,[7,8,9,8]) [9,8]

Variations…

remOne

remAll('d', 'coded') 'coe' remOne('d', 'coded') 'coed'

remUpto

remUpto('d','coded') 'ed'

remAll remAll

slide-55
SLIDE 55

Subsequences

def subseq( s, sbig )

s is the subsequence to find (or not) sbig is the bigger string in which we are looking for s

T or F?

subseq('ctg', 'tacggta') subseq('aliens', 'always frighten dragons') subseq('trogdor', 'that dragon is gone for good')

Why do these succeed? Or fail?

subseq('ctg', 'cataga')

Here there be NO dragons!

subseq('', 'cataga')

True or False?

slide-56
SLIDE 56

Try it!

def subseq( s, sbig ): """ returns True if s is a subseq. of sbig, False otherwise. Both are strings. """ if s == '': return True if

Write the other cases needed for subseq…

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:])

Algorithm design

1 2 3

Change remAll so that it removes only one e from L. (We could call it remOne.) Make changes to remAll so that it removes elements upto and including the first e in L. (We could call it remUpto.)

remOne(8,[7,8,9,8]) [7,9,8] remUpto('d','coded') 'ed'

slide-57
SLIDE 57

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 remAll( e, L[1:] )

from remAll to remOne

remOne(8,[7,8,9,8]) [7,9,8] remOne('d','coded') 'coed'

slide-58
SLIDE 58

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 L[1:]

from remOne to remUpto

remUpto(8,[7,8,9,8]) [9,8] remUpto('d','coded') 'ed'

slide-59
SLIDE 59

subseq( s, sbig )

What is a small (initial) piece of the problem? How would we describe it in terms of the inputs? What is left after handling this piece? Are there other functions we will need?

subseq('ctg', 'tacggta')

Subseq ~ sketching it out…

  • or -
slide-60
SLIDE 60

def subseq( s, sbig ): """ returns True if s is a subseq. of sbig; False otherwise. Both are strings. """ if s == '': return True

Subseq ~ trying (coding) it out…

Base case(s) Recursive step(s)

slide-61
SLIDE 61
slide-62
SLIDE 62
slide-63
SLIDE 63
slide-64
SLIDE 64

def subseq( s, sbig ): """ returns True if s is a subseq. of sbig; False otherwise. Both are strings. """ if s == '': return True

Let's try it in Sublime directly…

Subseq ~ trying (coding) it out…

Base case(s) Recursive step(s)

slide-65
SLIDE 65

def subseq( s, sbig ): """ returns True if s is a subseq. of sbig; False otherwise. Both are strings. """ if s == '': return True elif s[0] not in sbig: return False else: sbigrest = remUpto( s[0], sbig ) return subseq( s[1:], sbigrest )

Base case(s) Recursive step(s)

it

Subseq ~ trying (coding) it out…

Where are the useit and loseit here?

slide-66
SLIDE 66

def subseq( s, sbig ): """ returns True if s is a subseq. of sbig; False otherwise. Both are strings. """ if s == '': return True elif s[0] not in sbig: return False else: sbigrest = remUpto( s[0], sbig ) return subseq( s[1:], sbigrest )

Subseq ~ trying it out…

it

Base case(s) Recursive step(s)

slide-67
SLIDE 67

hw3pr2: LCS

Longest Common Subsequence 'HUMAN' 'CHIMPANZEE' 'CGCTGAGCTAGGCA...' 'ATCCTAGGTAACTG...'

Eye oneder if this haz
  • ther aplications?

+109more

slide-68
SLIDE 68

Why?

design of what? Code? Algorithms!

Screenshot from the ClustalX multiple subsequence alignment tool...

Subsequences (Jotto) (Sorting)

slide-69
SLIDE 69

What was gained (or lost) here?

Hey!?

Trinocular aliens

?

Phylogeny

slide-70
SLIDE 70

Subsequences @ HMC

Jane

host: figs parasites: wasps together:

slide-71
SLIDE 71

Jane's Challenge: 6 continents, 100s of species…

slide-72
SLIDE 72

Complete!

slide-73
SLIDE 73

also in hw3pr2: Jotto !

robot

  • tter

These are two cute

a word-guessing game… Let's try it!

slide-74
SLIDE 74

Getting started...

What will each of these jotto- scoring examples return? jotto('geese', 'seems') jotto('fluff', 'lulls') jotto('pears', 'diner') jotto('xylyl', 'slyly')

Extra! Which of these 8 is the cruellest hidden jotto word?

jotto(s1,s2) sort( L )

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

don't need to write any code for these (yet...)

Brainstorm algorithms for these problems -- what helper functions might help each one?

but think about how you'd approach them

LCS(s1,s2)

should return the longest common subsequence of strings s1 and s2

sort( [7,42,5] ) LCS( 'ctg', 'tagc' ) (see above for examples) [5,7,42] 'tg'

slide-75
SLIDE 75

Getting started...

What will each of these jotto- scoring examples return? jotto('geese', 'seems') jotto('fluff', 'lulls') jotto('pears', 'diner') jotto('xylyl', 'slyly')

Extra! Which of these 8 is the cruellest hidden jotto word?

jotto(s1,s2) sort( L )

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

don't need to write any code for these (yet...)

Brainstorm algorithms for these problems -- what helper functions might help each one?

but think about how you'd approach them

LCS(s1,s2)

should return the longest common subsequence of strings s1 and s2

3 2 2 4

slide-76
SLIDE 76

decipher( 'Weet bksa ed xecumeha 3!' )

slide-77
SLIDE 77

and have a great weekend, too ... !

decipher( 'Weet bksa ed xecumeha 3!' )