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…

Slides:



Advertisements
Similar presentations
CATHERINE AND ANNIE Python: Part 3. Intro to Loops Do you remember in Alice when you could use a loop to make a character perform an action multiple times?
Advertisements

CS 106 Introduction to Computer Science I 02 / 29 / 2008 Instructor: Michael Eckmann.
Computer Science 1620 Loops.
HW 1: Problems 3 & 4 EC 1 & 2.
This material in not in your text (except as exercises) Sequence Comparisons –Problems in molecular biology involve finding the minimum number of edit.
Logo Lesson 5 TBE Fall 2004 Farah Fisher. Prerequisites  Given a shape, use basic Logo commands and/or a procedure to draw the shape, with and.
Complexity (Running Time)
CS 106 Introduction to Computer Science I 10 / 15 / 2007 Instructor: Michael Eckmann.
EECS 110: Lec 6: Fractals and Trutles Aleksandar Kuzmanovic Northwestern University
Python. What is Python? A programming language we can use to communicate with the computer and solve problems We give the computer instructions that it.
What's ahead? Conway gives a whole new outlook on "loopy" ! John Conway 10/18 no class - Fall break 10/19 no new hw due 10/11 Dynamic & binary data 10/12.
Computer Science 1000 Spreadsheets II Permission to redistribute these slides is strictly prohibited without permission.
Working with Numbers in Alice - Converting to integers and to strings - Rounding numbers. - Truncating Numbers Samantha Huerta under the direction of Professor.
“Everything Else”. Find all substrings We’ve learned how to find the first location of a string in another string with find. What about finding all matches?
by Chris Brown under Prof. Susan Rodger Duke University June 2012
Lists in Python.
ICAPRG301A Week 4Buggy Programming ICAPRG301A Apply introductory programming techniques Program Bugs US Navy Admiral Grace Hopper is often credited with.
Iteration. Adding CDs to Vic Stack In many of the programs you write, you would like to have a CD on the stack before the program runs. To do this, you.
FUNCTIONS. Function call: >>> type(32) The name of the function is type. The expression in parentheses is called the argument of the function. Built-in.
IST 210: PHP BASICS IST 210: Organization of Data IST210 1.
CS 5 Today HW 9 (lab + 2 probs) due Sunday, 11/8 at midnight Dizzying arrays of possibilities… John Conway Carl Gauss This week’s credits: Exam 2 on Mon.,Tue.
Nonvisual Arrays and Recursion by Chris Brown under Prof. Susan Rodger Duke University June 2012.
Recursion, Complexity, and Sorting By Andrew Zeng.
Python Programming Chapter 6: Iteration Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
IT253: Computer Organization Lecture 3: Memory and Bit Operations Tonga Institute of Higher Education.
Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array.
Fall Week 4 CSCI-141 Scott C. Johnson.  Computers can process text as well as numbers ◦ Example: a news agency might want to find all the articles.
EECS 110: Lec 6: Fractals and Trutles Aleksandar Kuzmanovic Northwestern University
The Game of Life A simulation of "life". From simple rules, complex behavior arises Rules –A cell that is alive and has fewer than two live neighbors dies.
EECS 110: Lec 12: Mutable Data Aleksandar Kuzmanovic Northwestern University
This week in CS 5 HW 9 (2 problems) M/T sections W/Th sections due Sunday, 11/4 at midnight due Monday, 11/5 at midnight Recitation for HW9 -- Friday 11/2.
Homework 9 Due ( M & T sections ) ( W & Th sections ) at midnight Sun., 11/3 Mon., 11/4 Problems
CMSC 341 B- Trees D. Frey with apologies to Tom Anastasio.
Looping and Counting Lecture 3 Hartmut Kaiser
CS 121 Today Fractals and Turtles! The Koch Curve how random…
Scope When we create variables and functions, they are limited in where they are visible and where they can be referenced For the most part, the identifiers.
IS 313 Tomorrow… IS 313 Today? 9/16/09 - today: recursion and beyond! 9/23/09 - next wk: no meeting (DC) 9/30/09 - following wk: for & while Homework functions.
EECS 110 Recitation #3 Ning Xia Northwestern University.
UNIT 5.  The related activities of sorting, searching and merging are central to many computer applications.  Sorting and merging provide us with a.
1 Homework –Continue Reading K&R Chapter 2 –We’ll go over HW2 at end of class today –Continue working on HW3 Questions?
Overview Excel is a spreadsheet, a grid made from columns and rows. It is a software program that can make number manipulation easy and somewhat painless.
Function Definition by Cases and Recursion Lecture 2, Programmeringsteknik del A.
Lecture 6: Output 1.Presenting results in a professional manner 2.semicolon, disp(), fprintf() 3.Placeholders 4.Special characters 5.Format-modifiers 1.
Lesson 2: Reading a program. Remember: from yesterday We learned about… Precise language is needed to program Actors and Classes Methods – step by step.
Python Let’s get started!.
Ionut Trestian Northwestern University
EECS 110: Lec 7: Program Planning Aleksandar Kuzmanovic Northwestern University
Week 9 - Wednesday.  What did we talk about last time?  2D arrays  Queen attacking pawn example  Started Game of Life.
EECS 110: Lec 12: Mutable Data Aleksandar Kuzmanovic Northwestern University
 1 Searching. Why searching? Searching is everywhere. Searching is an essential operation for a dictionary and other data structures. Understand the.
8/3/2007CMSC 341 BTrees1 CMSC 341 B- Trees D. Frey with apologies to Tom Anastasio.
IST 210: PHP Basics IST 210: Organization of Data IST2101.
EECS 110: Lec 7: Program Planning Aleksandar Kuzmanovic Northwestern University
CS 121 Today Fractals and Turtles! The Koch Curve how random…
EECS 110: Lec 12: Mutable Data
EECS 110: Lec 7: Program Planning
CMSC201 Computer Science I for Majors Lecture 12 – Lists (cont)
EECS 110: Lec 6: Fractals and Trutles
More Loop Examples Functions and Parameters
HMC’s Galileo Auditorium Some of Cope’s generated MP3s:
Random numbers What does it mean for a number to be random?
B- Trees D. Frey with apologies to Tom Anastasio
Ionut Trestian Northwestern University
2D Array and Matrix.
Sorting "There's nothing in your head the sorting hat can't see. So try me on and I will tell you where you ought to be." -The Sorting Hat, Harry Potter.
B- Trees D. Frey with apologies to Tom Anastasio
Northwestern University
EECS 110: Lec 12: Mutable Data
More 2D Array and Loop Examples Functions and Parameters
2D Array and Matrix Application: Game of Life
Presentation transcript:

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

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!

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 !

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)

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

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

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

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

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

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:

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

An example “close to home” Write a program to model and analyze! this scenario... Hw5 Pr 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.

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?

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? Output RNG Can a computer generate them? A “black box” model of a random number generator.

Randomness vs. Determinism Are there random numbers?Can a computer generate them? The RNG revealed. Output YesNot without help! Periodic! p =

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

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

An example “close to home” 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

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…

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!

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

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

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

“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

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

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

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!

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)

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

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

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

Lsits’ flexibility Lists can hold ANY type of data double list A int list A “go” “red” “sox!” String list A

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

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

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…

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

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]

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

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)

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)

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!

Problem 2 -- Creating Life B = createNextLifeBoard( B ) old generation or "board" new generation or "board"

Problem 2 -- Creating Life B = update( B ) old generation or "board" new generation or "board"

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 life out there... B = update( B ) old generation or "board" new generation or "board"

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

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?

Lab & Homework…

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

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)