Ionut Trestian Northwestern University

Slides:



Advertisements
Similar presentations
Chapter 6 Lists and Dictionaries CSC1310 Fall 2009.
Advertisements

Computer Science & Engineering 2111 Text Functions 1CSE 2111 Lecture-Text Functions.
Dictionaries: Keeping track of pairs
Programming with Alice Computing Institute for K-12 Teachers Summer 2011 Workshop.
DICTIONARIES. The Compound Sequence Data Types All of the compound data types we have studies in detail so far – strings – lists – Tuples They are sequence.
CSC1016 Coursework Clarification Derek Mortimer March 2010.
HW 1: Problems 3 & 4 EC 1 & 2.
CS305j Introduction to Computing Two Dimensional Arrays 1 Topic 22 Two Dimensional Arrays "Computer Science is a science of abstraction -creating the right.
ABC’s of PowerPoint (Office 2007) Part 1: Basic Vocabulary Part 2: Cursors Part 3: Insert Your Text Part 4: Insert Your Pictures Part 5: Basic Tools &
It Seemed Like a Good Idea At the Time Suzanne (no last name given) at a university somewhere in the southwest US.
Multidimensional Data Many applications of databases are ``geographic'' = 2­dimensional data. Others involve large numbers of dimensions. Example: data.
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.
Games and Simulations O-O Programming in Java The Walker School
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.
Python Programming Chapter 10: Dictionaries Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
Programming for Linguists An Introduction to Python 24/11/2011.
Lists in Python.
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.
Chapter 6 Functions -- QuickStart. "The Practice of Computing Using Python", Punch & Enbody, Copyright © 2013 Pearson Education, Inc. What is a function?
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…
CS 5 Today Today: Midterm Exam #2 M/T 11/16-17/09, in class Life in 3d? filesdictionaries David Miller ! but there is an optional, ex. cr. circuit-building.
CS212: DATA STRUCTURES Lecture 10:Hashing 1. Outline 2  Map Abstract Data type  Map Abstract Data type methods  What is hash  Hash tables  Bucket.
Chapter 2 - Algorithms and Design
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.
Data Collections: Dictionaries CSC 161: The Art of Programming Prof. Henry Kautz 11/4/2009.
Introduction. 2COMPSCI Computer Science Fundamentals.
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.
VB Games: Preparing for Memory Brainstorm controls & events Parallel structures (again), Visibility, LoadPicture, User-defined procedures, Do While/Loop,busy.
EECS 110: Lec 17: Review for the Final Exam Aleksandar Kuzmanovic Northwestern University
Collecting Things Together - Lists 1. We’ve seen that Python can store things in memory and retrieve, using names. Sometime we want to store a bunch of.
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.
Topic 26 Two Dimensional Arrays "Computer Science is a science of abstraction -creating the right model for a problem and devising the appropriate mechanizable.
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
Built-in Data Structures in Python An Introduction.
What does C store? >>A = [1 2 3] >>B = [1 1] >>[C,D]=meshgrid(A,B) c) a) d) b)
1 Chapter 2 - Algorithms and Design print Statement input Statement and Variables Assignment Statement if Statement Flowcharts Flow of Control Looping.
Today’s Announcements Assignment 8 is due Project 2 is due 7/27/04 We will be skipping chapter 22 Test 3 (chapters 18-21) will be on 7/29/04 Tip of the.
Lecture 26: Reusable Methods: Enviable Sloth. Creating Function M-files User defined functions are stored as M- files To use them, they must be in the.
Homework 8 Due ( MT sections ) ( WTh sections ) at midnight Sun., 10/28 Mon., 10/29 Problems Reading is under week 7, however.
1 CSC 221: Introduction to Programming Fall 2012 Lists  lists as sequences  list operations +, *, len, indexing, slicing, for-in, in  example: dice.
Introduction to Computing Using Python Dictionaries: Keeping track of pairs  Class dict  Class tuple.
EECS 110: Lec 17: Review for the Final Exam Aleksandar Kuzmanovic Northwestern University
Python Programing: An Introduction to Computer Science
EECS 110: Lec 12: Mutable Data Aleksandar Kuzmanovic Northwestern University
IS 313 Today Schedule Week 0: files dictionaries You're saying that Python's got class ? Dictionaries and Classes Week 1: Week 2: Where we've been… Where.
EECS 110: Lec 13: Dictionaries Aleksandar Kuzmanovic Northwestern University
CS100 - PYTHON – EXAM 2 REVIEW -ONLY THE VITAL STUFF- PYTHON STRING METHODS, LOOPS, FILES, AND DICTIONARIES.
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
Lists/Dictionaries. What we are covering Data structure basics Lists Dictionaries Json.
Python Fundamentals: Complex Data Structures Eric Shook Department of Geography Kent State University.
Unit 4 – Chapter 4 Strings and Tuples. len() Function You can pass any sequence you want to the len() function and it will return the length of the sequence.
Practical Session 9 Computer Architecture and Assembly Language.
Reading Files >>> f = file( 'a.txt' ) >>> text = f.read() >>> text 'This is a file.\nLine 2\nLast line!\n' >>> f.close() In Python reading files is no.
EECS 110: Lec 13: Dictionaries
EECS 110: Lec 12: Mutable Data
CMSC201 Computer Science I for Majors Lecture 22 – Binary (and More)
Fundamentals of Programming II Backtracking with Stacks
Markov Model a language processing model
HMC’s Galileo Auditorium Some of Cope’s generated MP3s:
Files and Dictionaries
Topic 26 Two Dimensional Arrays
Ionut Trestian Northwestern University
2D Array and Matrix.
Northwestern University
How to use hash tables to solve olympiad problems
EECS 110: Lec 12: Mutable Data
Files and Dictionaries
2D Array and Matrix Application: Game of Life
Presentation transcript:

Ionut Trestian Northwestern University Recitation Homework 5 Ionut Trestian Northwestern University

The Game of Life: History Created by John Horton Conway, a British Mathematician Inspired by a problem presented by John Von Neumann: Build a hypothetical machine that can build copies of itself First presented in 1970, Scientific American

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

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

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

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

Problem 1 -- Creating Life updateNextLife(oldB, newB) old generation or "board" new generation or "board" 1 2 3 4 5 1 2 3 4 5 1 1 2 2 3 3 4 4 5 5

Problem 1 -- Creating Life updateNextLife(oldB, newB) old generation or "board" new generation or "board" 1 2 3 4 5 1 2 3 4 5 1 1 2 2 3 3 4 4 5 5

Problem 1 -- Details 0 represents an empty cell updateNextLife(oldB, newB) old generation or "board" new generation or "board" 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 http://www.math.com/students/wonders/life/life.html life out there...

Problem 1 – Main Loop def life( width, height ): """ will become John Conway's Game of Life... """ B = createBoard(width, height) csplot.showAndClickInIdle(B) while True: # run forever csplot.show(B) # show current B time.sleep(0.25) # pause a bit oldB = B B = createBoard( width, height ) updateNextLife( oldB, B ) # gets a new board

Problem 1 – Main Loop def life( width, height ): """ will become John Conway's Game of Life... """ B = createBoard(width, height) csplot.showAndClickInIdle(B) while True: # run forever csplot.show(B) # show current B time.sleep(0.25) # pause a bit oldB = B B = createBoard( width, height ) updateNextLife( oldB, B ) # gets a new board Update MUTATES the list B Why not just have update RETURN a new list? (i.e., why bother with mutation at all?)

Problem 2 - Markov Text Generation Technique for modeling any sequence of natural data 1st-order Markov Model Each item depends on only the item immediately before it . I like spam. I like toast and spam. I eat ben and jerry's ice cream too. The text file: For each word, keep track of the words that can follow it (and how often) The Model: I: like, like, eat like: spam, toast spam.: $ $: I, I, I toast: and eat: ben and: spam, jerry's ben: and jerry's: ice ice: cream cream: too. too.: $ We can repeat words to indicate frequency $ indicates beginning of a sentence

I like spam. I like spam. I like toast and jerry's ice cream too. Generative Markov Model Technique for modeling any sequence of natural data Each item depends on only the item immediately before it . A key benefit is that the model can generate feasible data! I like spam. I like spam. I like toast and jerry's ice cream too. Generating text: 1) start with the '$' string 2) choose a word following '$', at random. Call it w 3) choose a word following w, at random. And so on… 4) If w ends a sentence, '$' becomes the next word.

HW5 Pr 2: Need to be able to… Read text from a file Compute and store the model Generate the new text

Reading Files In Python reading files is no problem… >>> f = file( 'a.txt' ) >>> text = f.read() >>> text 'This is a file.\nLine 2\nLast line!\n' >>> f.close()

Files In Python reading files is no problem… >>> f = file( 'a.txt' ) >>> text = f.read() >>> text 'This is a file.\nLine 2\nLast line!\n' >>> f.close() opens the file and calls it f reads the whole file and calls it text text is a single string containing all the text in the file But how to process the text from here…? closes the file (closing Python does the same)

String Manupulation >>> text 'This is a file.\nLine 2\nLast line!\n' >>> print text This is a file. Line 2 Last line! >>> text.split() ['This', 'is', 'a', 'file.', 'Line', '2', 'Last', 'line!'] >>> lines = text.split('\n') >>> lines ['This is a file.', 'Line 2', 'Last line!', ''] Returns a list of the words in the string (splitting at spaces, tabs and newlines) Returns a list of the lines in the string (splitting at newlines)

HW5 Pr 2: Need to be able to… Read text from a file Compute and store the model Generate the new text

Lists vs. Dictionaries Lists are not perfect… L reference 5 42 L[0]

Lists vs. Dictionaries Lists are not perfect… reference 5 42 You can't choose what to name data. L L[0] L[1] L[0], L[1], …

Lists vs. Dictionaries Lists are not perfect… reference 5 42 You can't choose what to name data. L L[0] L[1] L[0], L[1], … You have to start at 0. L[1988] = 'dragon' L[1989] = 'snake'

Lists vs. Dictionaries Lists are not perfect… reference 5 42 You can't choose what to name data. L L[0] L[1] L[0], L[1], … You have to start at 0. L[1988] = 'dragon' L[1989] = 'snake' Some operations can be slow for big lists … if 'dragon' in L:

Lists vs. Dictionaries In Python a dictionary is a set of key - value pairs. >>> d = {} >>> d[1988] = 'dragon' >>> d[1989] = 'snake' >>> d {1988: 'dragon', 1989: 'snake'} >>> d[1988] 'dragon' >>> d[1987] key error It's a list where the index can be any immutable-type key.

Lists vs. Dictionaries In Python a dictionary is a set of key - value pairs. >>> d = {} >>> d[1988] = 'dragon' >>> d[1989] = 'snake' >>> d {1988: 'dragon', 1989: 'snake'} >>> d[1988] 'dragon' >>> d[1987] key error creates an empty dictionary, d 1988 is the key 'dragon' is the value 1989 is the key 'snake' is the value Anyone seen this before? Retrieve data as with lists… or almost ! It's a list where the index can be any immutable-type key.

delete a key (and its value) More on dictionaries Dictionaries have lots of built-in methods: >>> d = {1988: 'dragon', 1989: 'snake'} >>> d.keys() [ 1989, 1988 ] >>> d.has_key( 1988 ) True >>> d.has_key( 1969 ) False >>> d.pop( 1988 ) 'dragon' get all keys check if a key is present delete a key (and its value)

Markov Model Technique for modeling any sequence of natural data Each item depends on only the item immediately before it . I like spam. I like toast and spam. I eat ben and jerry's ice cream too. The text file: { 'toast': ['and'], 'and' : ['spam.', "jerry's"], 'like' : ['spam.', 'toast'], 'ben' : ['and'], 'I' : ['like', 'like', 'eat'], '$' : ['I', 'I', 'I'], The Model:

Extra credit Problem 3 printBumps( 4, '%', '#' ) % # % % # # % % %   % # % % # # % % % # # # % % % % # # # # printSquare( 3, '$' )   $ $ $ printRect( 4, 6, '%' ) % % % % printTriangle( 3, '@', True )   @ @ @ @ @ @ printTriangle( 3, '@', False )

Extra credit Problem 3 printStripedDiamond( 7, '.', '%' )   . . % . % . . % . % . % . % . . % . % . % . % . % . % . % . % . % . % . % . % . printCrazyStripedDiamond( 7, '.', '%', 2, 1 )   . . . . . % . . % . . . % . . . . % . . % . . % . . % . . % . . % . % . . % . . % . % . printDiamond( 3, '&' )   & & & & & &

EC Problem 4 A program that reads Flesch Index (FI) FI = 206.835 - 84.6 * numSyls/numWords - 1.015 * numWords/numSents numSyls is the total number of syllables in the text numWords is the total number of words in the text numSents is the total number of sentences in the text flesch() function

Extra Credit Problem 4 flesch() function Welcome to the text readability calculator!   Your options include: (1) Count sentences (2) Count words (3) Count syllables in one word (4) Calculate readability (9) Quit What option would you like? sentences(text) words(text) syllables(oneword)

Extra Credit Problem 4 Split Remove punctuation We will say that a sentence has occurred any time that one of its raw words ends in a period . question mark ? or exclamation point ! Note that this means that a plain period, question mark, or exclamation point counts as a sentence. A vowel is a capital or lowercase a, e, i, o, u, or y. A syllable occurs in a punctuation-stripped word whenever: Rule 1: a vowel is at the start of a word Rule 2: a vowel follows a consonant in a word Rule 3: there is one exception: if a lone vowel e or E is at the end of a (punctuation-stripped) word, then that vowel does not count as a syllable. Rule 4: finally, everything that is a word must always count as having at least one syllable.

Extra Credit Problem 5 Matrix Multiplication Gaussian elimination - another name for the process of using row operations in order to bring a matrix to reduced-row-echelon form. (1) Enter the size and values of an array (2) Print the array (3) Multiply an array row by a constant (4) Add one row into another (5) Add a multiple of one row to another (6) Solve! (7) Invert! [This is extra...] (9) Quit   Which choice would you like?

Extra Credit Problem 5 Matrix Multiplication for col in range(len(A)): # do the appropriate thing here   for row in range(len(A)): # do the appropriate thing here when row != col