Download presentation
Presentation is loading. Please wait.
1
EECS 110: Lec 8: Lists of Lists
Aleksandar Kuzmanovic Northwestern University
2
Midterm and Final Midterm: Final: Wednesday 4/26/2017 9:30am – 11:30am
Pancoe Life Science Pavilion (PLSAUD) Final: Wednesday 5/31/2017
3
EECS 110 today Hw #3 due Sunday… Computing with language
hw3pr1.py Computing with images 'Krphzrun 3, Sureohp 3: Wkh Fhdvdu Flskhu' hw3pr2.py hw3pr3.py
4
"Quiz" Nothing but the best! Hints: Hint:
Name(s): Hints: abs( x ) is built-in to Python Use bestWord as a guide: Write this function using max/min or recursively : def bestWord( L ): """ example code """ LOL = [ [scsc(w), w] for w in L ] bestPair = max( LOL ) return bestPair[1] def bestNumber( L ): """ returns the # in L closest to 42 """ Write this function however you like: Hint: Consider defining a helper function ! def mode( L ): """ returns the element appearing most often in L """
5
"Quiz" Solutions… def bestNumber( L ):
abs( x ) is built-in to Python Solutions… Hints: Use bestWord as a guide: def bestWord( L ): """ example code """ LOL = [ [scsc(w), w] for w in L ] bestPair = max( LOL ) return bestPair[1] Write this function using max/min: def bestNumber( L ): """ returns the # in L closest to 42 ""“ LOL = [ [abs(w-42), w] for w in L ] bestPair = min( LOL ) return bestPair[1]
6
"Quiz" Solutions… def numberOfTimes( w, L ):
Write this function however you like: Hint: Consider defining a helper function ! def numberOfTimes( w, L ): """ returns the # in times w repeats in L """ return sum([k==w for k in L]) def mode( L ): """ returns the element appearing most often in L """ LOL = [[numberOfTimes(w,L),w] for w in L] return max(LOL)[1]
7
Sorting a List Sorting a List
What is the input/output of the function? What data do we need to keep track of? [1,3,5,2,4] -> [5,4,3,2,1] We can keep track of the maximum or minimum element of the list
8
Sorting a List Sorting a List
If we had an easy way to find the maximum of the list, how could we use this to sort the list? We can just use recursion: Base case: If the length of the list is empty, return an empty list Recursive step: Find the maximum element in the list, then remove the maximum element from the list and concatinate it with the recursive call to the rest of the list.
9
Taking only one… def removeOne( e, L ):
""" this function removes one element e from the top level of the list L """ if len(L) == 0: return L # L is empty elif e == L[0]: return L[1:] # remove this one else: return L[0:1] + removeOne(e,L[1:]) # keep the non-e element and then keep going removeOne(42, [5,7,42,8,42]) removeOne('p', 'computer programming') [5,7,8,42] 'comuter programming'
10
sort(L) def sort( L ): """ a list of elements in L, sorted from hi to low """ if len(L) < 1: return L else:
11
sort(L) def sort( L ): """ a list of elements in L, sorted from hi to low """ if len(L) < 1: return L else: return [max(L)] + sort(removeOne( max(L), L ))
12
sort(L, maxFun) def sort( L, maxFun ):
""" a list of elements in L, sorted using maxFun """ if len(L) < 1: return L else: return
13
sort(L, maxFun) def sort( L, maxFun ):
""" a list of elements in L, sorted using maxFun """ if len(L) < 1: return L else: return [maxFun(L)] + sort(removeOne( maxFun(L), L )) Will this work?
14
sort(L, maxFun) def sort( L, maxFun ):
""" a list of elements in L, sorted using maxFun """ if len(L) < 1: return L else: return [maxFun(L)] + sort(removeOne( maxFun(L), L ), maxFun)
15
sort(L, maxFun) def sort( L, maxFun ):
""" a list of elements in L, sorted using maxFun """ if len(L) < 1: return L else: return [maxFun(L)] + sort(removeOne( maxFun(L), L ), maxFun) What happens if you call >>>sort( L, min )
16
Lights On!
17
Comprehending List Comprehensions
def runGenerations( L ): """ runGenerations keeps running evolve... """ print( L ) # display the list, L time.sleep(0.5) # pause a bit newL = evolve( L ) # evolve L into newL runGenerations( newL ) # recurse def evolve( L ): """ evolve takes in a list of integers, L, and returns a new list of integers considered to be the "next generation" N = len(L) # N now holds the size of the list L return [ setNewElement( L, i ) for i in range(N) ] def setNewElement( L, i, x=0 ): """ setNewElement returns the NEW list's ith element input L: any list of integers input i: the index of the new element to return input x: an extra, optional input for future use return L[i] + 1
18
Comprehending List Comprehensions
def evolve( L ): """ evolve takes in a list of integers, L, and returns a new list of integers considered to be the "next generation" """ N = len(L) # N now holds the size of the list L return [ setNewElement( L, i ) for i in range(N) ] def setNewElement( L, i, x=0 ): """ setNewElement returns the NEW list's ith element input L: any list of integers input i: the index of the new element to return input x: an extra, optional input for future use return L[i] + 1 >>> L = [42, 43, 44, 45, 46] >>> evolve(L) L 42 43 44 45 46 47 1 2 3 4 5 N 5 (i.e., len(L))
19
Comprehending List Comprehensions
def evolve( L ): """ evolve takes in a list of integers, L, and returns a new list of integers considered to be the "next generation" """ N = len(L) # N now holds the size of the list L return [ setNewElement( L, i ) for i in range(N) ] def setNewElement( L, i, x=0 ): """ setNewElement returns the NEW list's ith element input L: any list of integers input i: the index of the new element to return input x: an extra, optional input for future use return L[i] + 1 L [42, 43, 44, 45, 46] 1 2 3 4 >>> L = [42, 43, 44, 45, 46] >>> evolve(L) N 5 (i.e., len(L)) [ setNewElement( L, i ) for i in range(5) ] [0, 1, 2, 3, 4] [ , , , , ] i 1 2 3 4
20
Comprehending List Comprehensions
def evolve( L ): """ evolve takes in a list of integers, L, and returns a new list of integers considered to be the "next generation" """ N = len(L) # N now holds the size of the list L return [ setNewElement( L, i ) for i in range(N) ] def setNewElement( L, i, x=0 ): """ setNewElement returns the NEW list's ith element input L: any list of integers input i: the index of the new element to return input x: an extra, optional input for future use return L[i] + 1 L [[42, 43], [44, 45]] 1 >>> L = [[42, 43], [44, 45]] >>> evolve(L) [[43, 44], [45, 46]] N 2 (i.e., len(L)) [ setNewElement( L, i ) for i in range(2) ] What is i? What is L[i]?
21
Comprehending List Comprehensions
def evolve( L ): """ evolve takes in a list of integers, L, and returns a new list of integers considered to be the "next generation" """ N = len(L) # N now holds the size of the list L return [ setNewElement( L, i ) for i in range(N) ] def setNewElement( L, i, x=0 ): """ setNewElement returns the NEW list's ith element input L: any list of integers input i: the index of the new element to return input x: an extra, optional input for future use return L[i] + 1 Going deeper L [[42, 43], [44, 45]] 1 >>> L = [[42, 43], [44, 45]] >>> evolve(L) [[43, 44], [45, 46]] N 2 (i.e., len(L)) [ setNewElement( L, i ) for i in range(2) ] What is i? What is L[i]?
22
Comprehending List Comprehensions
[ L[j][0] for j in range(2) ] L [[42, 43], [44, 45]] [ [L[0][i]] for i in range(2) ] [ [ L[j][i]+1 for i in range(2) ] for j in range(2) ] [42,44] [42,43] [[43, 44], [45, 46]]
23
Comprehending List Comprehensions
[[42, 43], [44, 45]] [ [ setNewElement2d( L, i, j ) for i in range(2) ] for j in range(2) ] def setNewElement2d( L, i, j, x=0, y=0 ): """ setNewElement returns the NEW list's ith element input L: any list of integers input i: the index of the new element to return input x: an extra, optional input for future use """ return L[j][i] + 1
24
Representing Pictures
25
Digital representations of pictures
Grid of Pixels—each Pixel has a color But how is color represented?
26
RGB Model for Representing Color
Most popular, but not only one Each pixel represented in three parts (100, 0, 0) R G B So every Pixel has some amount of Red some amount of Green and some amount of Blue HOW MUCH?
27
Color “levels” Each color component or “channel” is represented with a single byte 1 byte = 8 bits; which can represent numbers from 0 to 255 (2^8 – 1) Each RGB value is between 0 and 255 Examples… (255, 255, 255): white (150, 150, 150): gray
28
Brightening a Picture def modify(pic):
""" modify modifies an image to make it brighter """ pixels = getPixels(pic) if len(pixels) == 0: return newPixels = [ [setNewPixel( pixels, row, col ) for col in range(len(pixels[0]))] for row in range(len(pixels))] setPixels(pic, newPixels) def setNewPixel( pixels, row, col ): """ setNewPixel returns the NEW imanges (row, col) (r,g,b) value input pixels: a 2D list containing RGB information in the pixels in a picture input row: the row of the pixel in question input col: the column of the pixel in question """ rval= min(pixels[row][col][0]+30, 255) gval = min(pixels[row][col][1]+30, 255) bval = min(pixels[row][col][2]+30, 255) return (rval, gval, bval)
29
Representing the Pixels in a Picture
[ [(3, 10, 100), (3, 11, 110)], [(3, 10, 200), (10, 110, 290)] ] Width: len(pixels[0]) Height: len(pixels) 2x2 pixel image
30
Tuples vs. Lists Tuples use ( ); lists use [ ]
[ [(3, 10, 100), (3, 11, 110)], [(3, 10, 200), (10, 110, 290)] ] Tuples use ( ); lists use [ ] But otherwise, they are the same… (for now, almost) >>> t = (1, 2, 3) >>> t[1] 2 >>> t[1:] (2, 3) >>> (x, y, z) = t >>> x 1 >>> y
31
Brightening a Picture def modify(pic):
""" modify modifies an image to make it brighter """ pixels = getPixels(pic) if len(pixels) == 0: return newPixels = [ [setNewPixel( pixels, row, col ) for col in range(len(pixels[0]))] for row in range(len(pixels))] setPixels(pic, newPixels) def setNewPixel( pixels, row, col ): """ setNewPixel returns the NEW imanges (row, col) (r,g,b) value input pixels: a 2D list containing RGB information in the pixels in a picture input row: the row of the pixel in question input col: the column of the pixel in question """ rval= min(pixels[row][col][0]+30, 255) gval = min(pixels[row][col][1]+30, 255) bval = min(pixels[row][col][2]+30, 255) return (rval, gval, bval)
32
"Quiz“ It's all clear to me now!
Name(s): Write a function that tints the top half of the picture red (how red is up to you): def setNewPixel( pixels, row, col ): """ setNewPixel returns the NEW image's (row, col) (r,g,b) value """ Write a function that copies the top half of an image to the bottom half. def setNewPixel( pixels, row, col ): """ setNewPixel returns the NEW image's (row, col) (r,g,b) value """ Want more? How would you turn only the sky red?
33
"Quiz“ It's all clear to me now!
Name(s): Write a function that tints the top half of the picture red (how red is up to you): def setNewPixel( pixels, row, col ): """ setNewPixel returns the NEW image's (row, col) (r,g,b) value """ if row <= len(pixels)//2: rval = min(pixels[row][col][0]+75,255) else: rval = pixels[row][col][0] return (rval, pixels[row][col][1], pixels[row][col][2]) Write a function that copies the top half of an image to the bottom half. def setNewPixel( pixels, row, col ): """ setNewPixel returns the NEW image's (row, col) (r,g,b) value """ Want more? How would you turn only the sky red?
34
"Quiz“ It's all clear to me now!
Name(s): Write a function that tints the top half of the picture red (how red is up to you): def setNewPixel( pixels, row, col ): """ setNewPixel returns the NEW image's (row, col) (r,g,b) value """ if row <= len(pixels)//2: rval = min(pixels[row][col][0]+75,255) else: rval = pixels[row][col][0] return (rval, pixels[row][col][1], pixels[row][col][2]) Write a function that copies the top half of an image to the bottom half. def setNewPixel( pixels, row, col ): """ setNewPixel returns the NEW image's (row, col) (r,g,b) value """ if row > len(pixels)//2: return pixels[row-len(pixels)//2][col] else: return pixels[row][col] Want more? How would you turn only the sky red?
35
Caesar Cipher: encipher
'gv vw dtwvg' 'hw wx euxwh' 'ix xy fvyxi' 'jy yz gwzyj' 'kz za hxazk' 'la ab iybal' encipher( 'gv vw dtwvg' , 0 ) returns encipher( 'gv vw dtwvg' , 1 ) returns encipher( 'gv vw dtwvg' , 2 ) returns encipher( 'gv vw dtwvg' , 3 ) returns encipher( 'gv vw dtwvg' , 4 ) … returns encipher( 'gv vw dtwvg' , 5 ) returns encipher( 'gv vw dtwvg' , 25 ) 'fu uv csvuf' returns should return the string s with each alphabetic character shifted/wrapped by n places in the alphabet encipher( S , n )
36
How Strings are Represented and Stored?
American Standard Code for Information Interchange ASCII is a table that tells the computer how to represent characters as bits! value: '*' bits type: str name: Identical bits are stored in each variable! 8 bits = 1 byte The types determine how to interpret the bits; the names don't matter at all… value: 42 The SAME bits represent integers, if the variable has type int instead of str bits type: int name:
37
American Standard Code for Information Interchange
ASCII American Standard Code for Information Interchange ASCII is a table that tells the computer how to represent characters as #s chr convert to char. convert to number ord
38
chr and ord abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ
ASCII VALUES 97 99 101 103 105 107 109 111 113 115 117 119 122 ABCDEFGHIJKLMNOPQRSTUVWXYZ 65 67 69 71 73 75 77 79 81 83 85 87 90 Input: a string of one character, c ord( c ) Output: an integer, the ASCII value of c CONVERTERS Input: an integer in range(255) chr( n ) Output: a one-char. string of that ASCII value [ [i,chr(i)] for i in range(128) ] try these! [ ord(i) for i in '**** CS! ****' ]
39
abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ
chr and ord abcdefghijklmnopqrstuvwxyz ASCII VALUES 97 99 101 103 105 107 109 111 113 115 117 119 122 ABCDEFGHIJKLMNOPQRSTUVWXYZ 65 67 69 71 73 75 77 79 81 83 85 87 90 ord('a') is ? chr(66) is ? What is chr( ord('i')+13 ) ? What is chr( ord('P')+13 ) ?
40
abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ
chr and ord abcdefghijklmnopqrstuvwxyz ASCII VALUES 97 99 101 103 105 107 109 111 113 115 117 119 122 ABCDEFGHIJKLMNOPQRSTUVWXYZ 65 67 69 71 73 75 77 79 81 83 85 87 90 ord('a') is 97 chr(66) is ? What is chr( ord('i')+13 ) ? What is chr( ord('P')+13 ) ?
41
abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ
chr and ord abcdefghijklmnopqrstuvwxyz ASCII VALUES 97 99 101 103 105 107 109 111 113 115 117 119 122 ABCDEFGHIJKLMNOPQRSTUVWXYZ 65 67 69 71 73 75 77 79 81 83 85 87 90 ord('a') is 97 chr(66) is 'B' What is chr( ord('i')+13 ) ? What is chr( ord('P')+13 ) ?
42
abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ
chr and ord abcdefghijklmnopqrstuvwxyz ASCII VALUES 97 99 101 103 105 107 109 111 113 115 117 119 122 ABCDEFGHIJKLMNOPQRSTUVWXYZ 65 67 69 71 73 75 77 79 81 83 85 87 90 ord('a') is 97 chr(66) is 'B' What is chr( ord('i')+13 )'v' What is chr( ord('P')+13 ) ?
43
abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ
chr and ord abcdefghijklmnopqrstuvwxyz ASCII VALUES 97 99 101 103 105 107 109 111 113 115 117 119 122 ABCDEFGHIJKLMNOPQRSTUVWXYZ 65 67 69 71 73 75 77 79 81 83 85 87 90 ord('a') is 97 chr(66) is 'B' What is chr( ord('i')+13 )'v' What is chr( ord('P')+13 ) ']' How can we wrap this around?
44
Rot 13 def adv13( c ): """ rotates c by 13 chars, "wrapping" as needed
NON-LETTERS DO NOT CHANGE! """ if 'a' <= c <= 'z': neword = ord(c) + 13 if neword <= ord('z'): return chr(neword) # no wrapping else: return elif How would you rotate an entire string?
45
Rot 13 def adv13( c ): """ rotates c by 13 chars, "wrapping" as needed
NON-LETTERS DO NOT CHANGE! """ if 'a' <= c <= 'z': neword = ord(c) + 13 if neword <= ord('z'): return chr(neword) # no wrapping else: return chr(ord('a')+neword-ord('z')-1) elif How would you rotate an entire string?
46
Rot 13 def adv13( c ): """ rotates c by 13 chars, "wrapping" as needed
NON-LETTERS DO NOT CHANGE! """ if 'a' <= c <= 'z': neword = ord(c) + 13 if neword <= ord('z'): return chr(neword) # no wrapping else: return chr(ord('a')+neword-ord('z')-1) elif 'A' <= c <= 'Z': # same as above, only use 'A' and 'Z' return c How would you rotate an entire string?
47
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.' >>> decipher('gv vw dtwvg') >>> decipher('Uifz xpsl ju pvu xjui b qfodjm!') But how ?
48
Caesar Cipher: decipher
gv vw dtwvg hw wx euxwh ix xy fvyxi jy yz gwzyj kz za hxazk la ab iybal mb bc jzcbm nc cd kadcn od 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 Caesar Brutus >>> decipher('gv vw dtwvg') Strategy using max: (1) consider all possible answers (2) give them each a score (3) use our techniques to get max Score for "Englishness"? up to you… all 26 possibilities
49
Caesar Cipher: decipher
[0, 'cr rs zpsrc'] [0, 'gv vw dtwvg'] [0, 'jy yz gwzyj'] [0, 'mb bc jzcbm'] [0, 'qf fg ndgfq'] [0, 'wl lm tjmlw'] [1, 'bq qr yorqb'] [1, 'ds st aqtsd'] [1, 'nc cd kadcn'] [1, 'vk kl silkv'] [1, 'xm mn uknmx'] [2, 'ap pq xnqpa'] [2, 'hw wx euxwh'] [2, 'ix xy fvyxi'] [2, 'kz za hxazk'] [2, 'rg gh oehgr'] [2, 'sh hi pfihs'] [2, 'uj jk rhkju'] [2, 'yn no vlony'] [3, 'fu uv csvuf'] [3, 'pe ef mcfep'] [3, 'ti ij qgjit'] [3, 'zo op wmpoz'] [4, 'et tu brute'] [4, 'la ab iybal'] [4, 'od de lbedo'] Caesar Brutus >>> decipher('gv vw dtwvg') 'od de lbedo' Strategy using max: (1) consider all possible answers (2) give them each a score (3) use our techniques with max number-of-vowels score won't always be correct! all 26 possibilities
50
Caesar Cipher: decipher
[0.4680, 'jy yz gwzyj'] [0.4960, 'mb bc jzcbm'] [0.5420, 'uj jk rhkju'] [0.5567, 'ix xy fvyxi'] [0.5597, 'qf fg ndgfq'] [0.5718, 'fu uv csvuf'] [0.5753, 'bq qr yorqb'] [0.5833, 'kz za hxazk'] [0.5859, 'xm mn uknmx'] [0.5880, 'gv vw dtwvg'] [0.5902, 'vk kl silkv'] [0.6110, 'ap pq xnqpa'] [0.6304, 'zo op wmpoz'] [0.6318, 'wl lm tjmlw'] [0.6717, 'cr rs zpsrc'] [0.6735, 'hw wx euxwh'] [0.6963, 'nc cd kadcn'] [0.7153, 'ti ij qgjit'] [0.7398, 'la ab iybal'] [0.7442, 'yn no vlony'] [0.7867, 'pe ef mcfep'] [0.7880, 'sh hi pfihs'] [0.7918, 'rg gh oehgr'] [0.8213, 'ds st aqtsd'] [0.8609, 'od de lbedo'] [0.9082, 'et tu brute'] Caesar Brutus >>> decipher('gv vw dtwvg') 'et tu brute' Strategy using max: (1) consider all possible answers (2) give them each a score (3) use our techniques with max letter- probability score not always correct, but better! all 26 possibilities
51
'Weet bksa ed Xecumeha 3!'
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.