Presentation is loading. Please wait.

Presentation is loading. Please wait.

The not-so-subtle art of singling out the best (and worst) of anything… Computing with language Computing to the max You know this would make me hungry…

Similar presentations


Presentation on theme: "The not-so-subtle art of singling out the best (and worst) of anything… Computing with language Computing to the max You know this would make me hungry…"— Presentation transcript:

1 The not-so-subtle art of singling out the best (and worst) of anything… Computing with language Computing to the max You know this would make me hungry… if it weren't 7 pm! Battle-tested ciphers - and how to break them ! Consider literature a bunch of strings ? 'm&ms' [ 0, 42 ] a comparison comparison [ 4, 2 ] True 'True' 'coffee' > or < Drawn Inward Fall leaves when leaves fall. Seasons by Mike Maguire

2 What's ahead? Conway gives a whole new outlook on "loopy" ! John Conway 10/21 no class - Fall break 10/22 encipher/decipher due 10/14 Dynamic data - references 10/15 ASCII art due 11/4 Objects and naming 2 11/5 Markov text due 10/28 Objects and naming 1 10/29 Wandering and Life due 11/5 Project proposals due I'm a head!

3 Recursive max def max( L ): if len(L) < 2: return L[0] elif L[0] < L[1]: return max( L[1:] ) else: return max( L[0:1] + L[2:] ) A recipe for life ? The hard part is knowing what we want to maximize! and python already has it for us! If there is only 1 element, it's the max! If the first element is less than the second, "forget about" the first one and find the max of everything else… But if the second element is smaller, forget about it and take the max of everything else !

4 Out of the box… If we want the highest price… What if the months are in there, as well? If we want the final word: or if we want the initial word… ? 'sep''jul''may''mar''jan''nov' 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) And I thought $100 was overpriced! max( [475.5, 458.0, 441.3, 470.8, 532.8, 520.9] ) max( [ [475.5,'nov'], [458.0,'jan'], [441.3,'mar'], [470.8,'may'], [532.8,'jul'], [520.9,'sep'] ] ) min(L)

5 "max" word def maxWord( L ): """ finds the "max" word from L, a list of words """ return max(L) L = [ "to","be","or","not","to","be","that","is","the","question" ]

6 "max" word - part 2! def maxWord( L ): """ finds the "max" word from L, a list of words """ return max(L) ?? L = [ "to","be","or","not","to","be","that","is","the","question" ] How could we redefine max!? longest word?most times? lowest scrabble score? This is max?

7 "Best" word ~ longest def bestWord( L ): """ finds the "best" word from L, a list of words """ L = [ "to","be","or","not","to","be","that","is","the","question" ]

8 "Best" word ~ lowest scrabble score def scrabbleScore(w): # see homework #2! def bestWord( L ): """ finds the "best" word from L, a list of words here, "best" means lowest scrabble score """ Let's abbreviate this function as scsc(w) Add printing as you see fit!

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

10 "Coding Challenge" Nothing but the best! def bestNumber( L ): """ returns the # in L closest to 42 """ Hint: abs( x ) is built-in to Python Use bestWord as a guide Write these two functions: def mode( L ): """ returns the element appearing most often in L """ Hint: You may want to define a helper function !

11 Try it… def bestNumber( L ): """ returns the # in L closest to 42 """ Hint: abs( x ) is built-in to Python Use bestWord as a guide Write this function:

12 Try it… def mode( L ): """ returns the element appearing most often in L """ Hint: You may want to define a helper function !

13 An example “close to home” Write a program to model and analyze! this scenario... Hw5 Pr1... 25262728502423220 An overworked CGU student (S) leaves Starbucks after their “late-night” breakfast and, each moment, randomly stumbles toward campus (W) or toward home (E) CGUhome (E) (W) Starbucks S Once the student arrives at home or the classroom, the trip is complete. The program should then print the total number of steps taken.

14 Some random info… import random random.choice( L ) random.uniform(low,hi) random.choice( ['drucker', 'sisat', 'sah'] ) random.uniform(41.9,42.1) chooses 1 element from the list L chooses a random float from low to hi for more explanation, try dir(random) or help(random) How likely is this to return 42 ? How would you get a random int from 0 to 9?

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

16 An example: the ASCII equalizer Notes… first ~ all the same second ~ random lengths third ~ changing by 1

17 Randomness vs. Determinism Are there random numbers? Output RNG Can a computer generate them? A “black box” model of a random number generator.

18 Randomness vs. Determinism Are there random numbers?Can a computer generate them? The RNG revealed. Output YesNot without help! http://en.wikipedia.org/wiki/Mersenne_twister Periodic! p = 2 19937 -1

19 True Randomness ! LavaRnd’s lava lamps using a chaotic physical system to seed random number generators (Patent 5,732,138: "Method for seeding a pseudo- random number generator with a cryptographic hash of a digitization of a chaotic system.") This has since been “improved”… www.wired.com/wired/archive/11.08/random.html

20 The two Monte Carlos Monte Carlo casino, Monaco Making random numbers work for you! Monte Carlo methods, Math/CS

21 An example “close to home”... 25262728502423220 An overworked CGU student (S) leaves Starbucks after their “late-night” breakfast and, each moment, randomly stumbles toward campus (W) or toward home (E) CGUhome (E) (W) Starbucks Write a program to model and analyze! this scenario... S Once the student arrives at home or the classroom, the trip is complete. The program should then print the total number of steps taken. 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 Hw5 Pr1

22 uses a basic random- walk model with unequal step probabilities Gel electrophoresis Used to separate proteins and nucleic acids (DNA) from a biological sample. Molecules with different properties travel different distances. one of many applications for random walks…

23 print: Making programs talk to you! Essential for debugging … 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!

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

25 The first bug Grace Hopper “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.” from the UNIVAC 1

26 Reference vs. Value Changeable types:Unchangeable types: list tuple string int float bool L L[0]L[1]L[2] Reference, Pointer, id L = [7,11,'hi'] x 7 11 'hi' 42 x = 42

27 “Pass By Value” def main() """ calls conform """ print " Welcome to Conformity, Inc. " fav = 7 conform(fav) print " My favorite number is", fav def conform(fav) """ sets input to 42 """ fav = 42 return fav 7 fav

28 7 “Pass By Value” def main() """ calls conform """ print " Welcome to Conformity, Inc. " fav = 7 conform(fav) print " My favorite number is", fav def conform(fav) """ sets input to 42 """ fav = 42 return fav 7 fav PASS BY VALUE “Pass by value” means that data is copied when sent to a method 42

29 Passing lists by value… def main() """ calls conform2 """ print " Welcome to Conformity, Inc. " fav = [ 7, 11 ] conform2(fav) print " My favorite numbers are", fav def conform2(fav) """ sets all of fav to 42 """ fav[0] = 42 fav[1] = 42 What gets passed by value here? fav L[0]L[1] 7 11 fav

30 Passing lists by value… def main() """ calls conform2 """ print " Welcome to Conformity, Inc. " fav = [ 7, 11 ] conform2(fav) print " My favorite numbers are", fav def conform2(fav) """ sets all of fav to 42 """ fav[0] = 42 fav[1] = 42 fav L[0]L[1] 7 11 fav can change data elsewhere! The reference is copied!

31 The conclusion You can change the contents of lists in functions that take those lists as input. Those changes will be visible everywhere. (actually, lists or any mutable objects) (immutable objects are safe, however)

32 Views of the world Engineers think their equations approximate reality.

33 Views of the world Engineers think their equations approximate reality. Physicists think reality approximates their equations.

34 Views of the world Engineers think their equations approximate reality. Physicists think reality approximates their equations. Mathematicians don't care.

35 Views of the world Axioms Definitions Creating structure from a few simple facts... Creating structure from a few simple actions... if/else while for arithmetic operations variables arrays ProofAlgorithm Engineers think their equations approximate reality. Physicists think reality approximates their equations. Mathematicians don't care.

36 Lists’ flexibility Lists can hold ANY type of data A = [ 42., 75., 70. ] 42.0 75.0 70.0 float list A they don’t have to be horizontal lists!

37 42.0 75.0 70.0 double list A they don’t have to be horizontal lists! Lists’ flexibility Lists can hold ANY type of data A = [ 42., 75., 70. ] 42.0 75.0 70.0 float list A

38 Lsits’ flexibility Lists can hold ANY type of data 42.0 75.0 70.0 double list A 42 7 -11 int list A “go” “red” “sox!” String list A

39 2d lists or arrays Lists can hold ANY type of data -- including lists ! list A A = [ [1,2,3,4], [5,6], [7,8,9,10,11] ]

40 list A 2d arrays list A[0] A[1] A[2] Lists can hold ANY type of data -- including lists ! A = [ [1,2,3,4], [5,6], [7,8,9,10,11] ]

41 list A Jagged arrays list A[0] A[1] A[2] Lists can hold ANY type of data -- including lists ! A = [ [1,2,3,4], [5,6], [7,8,9,10,11] ] Rows within 2d arrays need not be the same length…

42 list A A[0] A[1] A[2] Lists can hold ANY type of data -- including lists ! A = [ [1,2,3,4], [5,6], [7,8,9,10,11] ] Rows within 2d arrays need not be the same length… We will not use jagged arrays at least in hw 10

43 Rectangular arrays list A A[0] A[1] A[2] How many rows does A have, in general ? How many columns does A have, in general ? What does each component of A[1][2] mean ? A[1][2] = 42 A[2][3] A[0][0]

44 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

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

46 Problem 2 -- “Life” Evolutionary rules Grid World Everything depends on a cell’s eight neighbors red cells are alive white cells are empty 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) John Conway

47 Problem 2 -- Life Evolutionary rules Grid World Everything depends on a cell’s eight neighbors red cells are alive white cells are empty 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)

48 Problem 2 -- Life Evolutionary rules Grid World Everything depends on a cell’s eight neighbors red cells are alive white cells are empty 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)

49 Problem 2 -- Life Evolutionary rules Grid World Everything depends on a cell’s eight neighbors red cells are alive white cells are empty 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) life out there... Keep going!

50 Problem 2 -- Creating Life 0123450 12345 0 1 2 3 4 5 0 1 2 3 4 5 B = createNextLifeBoard( B ) old generation or "board" new generation or "board"

51 Problem 2 -- Creating Life 0123450 12345 0 1 2 3 4 5 0 1 2 3 4 5 B = update( B ) old generation or "board" new generation or "board"

52 Problem 2 -- Details 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... B = update( B ) old generation or "board" new generation or "board"

53 Problem 2 -- to  and beyond! Are there stable life configurations? Are there oscillating life configurations? Are there self-propagating life configurations? "rocks" "plants" "animals" period 3 period 2

54 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? How sophisticated can the structures in the life universe be? Google for GOLLY, Game of Life Are all feasible configurations reachable?

55 Lab & Homework…

56 import sys for i in range(4): for j in range(8): sys.stdout.write('#') print software object representing the screen's standard output Without extra spaces… Output ######## method (function) that prints only its input

57 Files Want to analyze one of your papers? f = open('paper.txt') max(words) min(words) text = f.read() words = text.split() 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. or anything else you might want to investigate… ! f becomes the "file object" representing paper.txt in this case. You will first need to save your file as "plain text" or else all the special formatting characters will still be in there! text is now one BIG string words is now one BIG list of words (strings)


Download ppt "The not-so-subtle art of singling out the best (and worst) of anything… Computing with language Computing to the max You know this would make me hungry…"

Similar presentations


Ads by Google