ionut trestian northwestern university

33
Recitation Homework 5 Ionut Trestian Northwestern University

Upload: rhoda-richard

Post on 08-Jan-2018

225 views

Category:

Documents


0 download

DESCRIPTION

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

TRANSCRIPT

Page 1: Ionut Trestian Northwestern University

Recitation Homework 5

Ionut TrestianNorthwestern University

Page 2: Ionut Trestian Northwestern University

The Game of Life: History

• Created by John Horton Conway,a British Mathematician

• Inspired by a problem presentedby John Von Neumann:– Build a hypothetical machine that can build copies of itself

• First presented in 1970, Scientific American

Page 3: Ionut Trestian Northwestern University

Problem 1 -- “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 anexisting cell alive

• Any other number of neighbors kill the central cell (or keep it dead)

Page 4: Ionut Trestian Northwestern University

Problem 1 -- 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 anexisting cell alive

• Any other number of neighbors kill the central cell (or keep it dead)

Page 5: Ionut Trestian Northwestern University

Problem 1 -- 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 anexisting cell alive

• Any other number of neighbors kill the central cell (or keep it dead)

Page 6: Ionut Trestian Northwestern University

Problem 1 -- 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 anexisting cell alive

• Any other number of neighbors kill the central cell (or keep it dead)

life out there...

Keep going!

Page 7: Ionut Trestian Northwestern University

Problem 1 -- Creating Life

0 1 2 3 4 50 1 2 3 4 5

0

1

2

3

4

5

0

1

2

3

4

5

updateNextLife(oldB, newB)

old generation or "board" new generation or "board"

Page 8: Ionut Trestian Northwestern University

Problem 1 -- Creating Life

0 1 2 3 4 50 1 2 3 4 5

0

1

2

3

4

5

0

1

2

3

4

5

old generation or "board" new generation or "board"

updateNextLife(oldB, newB)

Page 9: Ionut Trestian Northwestern University

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

http://www.math.com/students/wonders/life/life.html

old generation or "board" new generation or "board"

life out there...

updateNextLife(oldB, newB)

Page 10: Ionut Trestian Northwestern University

Problem 1 – Main Loopdef 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

Page 11: Ionut Trestian Northwestern University

Problem 1 – Main Loopdef 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

Why not just have update RETURN a new list? (i.e., why bother with mutation at all?)

Update MUTATES the list B

Page 12: Ionut Trestian Northwestern University

Problem 2 - Markov Text Generation

The text file: I like spam. I like toast and spam. I eat ben and jerry's ice cream too.

Technique for modeling any sequence of natural data Each item depends on only the item immediately before it .

The Model:

1st-order Markov Model

For each word, keep track of the words that can follow it (and how often)

I: like, like, eatlike: spam, toastspam.: $$: I, I, Itoast: andeat: benand: spam, jerry's

ben: andjerry's: iceice: creamcream: too.too.: $

• We can repeat wordsto indicate frequency

• $ indicates beginningof a sentence

Page 13: Ionut Trestian Northwestern University

Generative Markov ModelTechnique 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.

Page 14: Ionut Trestian Northwestern University

HW5 Pr 2: Need to be able to…

Read text from a file

Compute and store the model

Generate the new text

Page 15: Ionut Trestian Northwestern University

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

Page 16: Ionut Trestian Northwestern University

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

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

closes the file (closing Python does the same)

But how to process the text from here…?

Page 17: Ionut Trestian Northwestern University

String Manupulation>>> text'This is a file.\nLine 2\nLast line!\n'>>> print textThis is a file.Line 2Last line!

>>> text.split()['This', 'is', 'a', 'file.', 'Line', '2', 'Last', 'line!']>>> text'This is a file.\nLine 2\nLast line!\n'>>> 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)

Page 18: Ionut Trestian Northwestern University

HW5 Pr 2: Need to be able to…

Read text from a file

Compute and store the model

Generate the new text

Page 19: Ionut Trestian Northwestern University

Lists vs. Dictionaries

Lists are not perfect…

LL[0] L[1]

reference

5 42

Page 20: Ionut Trestian Northwestern University

Lists vs. Dictionaries

Lists are not perfect…

You can't choose what to name data.

L[0], L[1], …

LL[0] L[1]

reference

5 42

Page 21: Ionut Trestian Northwestern University

Lists vs. Dictionaries

Lists are not perfect…

L[1988] = 'dragon'

You can't choose what to name data.

You have to start at 0.

L[0], L[1], …

LL[0] L[1]

reference

5 42

L[1989] = 'snake'

Page 22: Ionut Trestian Northwestern University

Lists vs. Dictionaries

Lists are not perfect…

L[1988] = 'dragon'

You can't choose what to name data.

You have to start at 0.

Some operations can be slow for big lists …

L[0], L[1], …

LL[0] L[1]

reference

5 42

L[1989] = 'snake'

if 'dragon' in L:

Page 23: Ionut Trestian Northwestern University

Lists vs. Dictionaries

In Python a dictionary is a set of key - value pairs.

It's a list where the index can be any immutable-type key.

>>> d = {}

>>> d[1988] = 'dragon'

>>> d[1989] = 'snake'>>> d

{1988: 'dragon', 1989: 'snake'}

>>> d[1988]'dragon'

>>> d[1987]

key error

Page 24: Ionut Trestian Northwestern University

Lists vs. Dictionaries

In Python a dictionary is a set of key - value pairs.

It's a list where the index can be any immutable-type key.

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

Page 25: Ionut Trestian Northwestern University

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'

delete a key (and its value)

check if a key is present

get all keys

Page 26: Ionut Trestian Northwestern University

Markov Model

{ 'toast': ['and'], 'and' : ['spam.', "jerry's"], 'like' : ['spam.', 'toast'], 'ben' : ['and'], 'I' : ['like', 'like', 'eat'], '$' : ['I', 'I', 'I'],

The text file: I like spam. I like toast and spam. I eat ben and jerry's ice cream too.

Technique for modeling any sequence of natural data Each item depends on only the item immediately before it .

The Model:

Page 27: Ionut Trestian Northwestern University

Extra credit Problem 3printSquare( 3, '$' ) $ $ $$ $ $$ $ $

printRect( 4, 6, '%' ) % % % %% % % %% % % %% % % %% % % %% % % %

printTriangle( 3, '@', True ) @@ @@ @ @ printTriangle( 3, '@', False ) @ @ @@ @@

printBumps( 4, '%', '#' ) %#%% %# ##%% %% % %# # ## ##%% %% % %% % % %# # # ## # ## ##

Page 28: Ionut Trestian Northwestern University

printDiamond( 3, '&' ) & & & & & & & & &

printStripedDiamond( 7, '.', '%' ) . . % . % . . % . % . % . % . . % . % . %. % . % . % . % . % . % . . % . % . % . % . . % . % . .

printCrazyStripedDiamond( 7, '.', '%', 2, 1 ) . . . . . % . . % . . . % . . . . % . . %. . % . . % . . % . . % . % . . % . . . % . . % . % . .

Extra credit Problem 3

Page 29: Ionut Trestian Northwestern University

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

Page 30: Ionut Trestian Northwestern University

Extra Credit Problem 4flesch() 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)

Page 31: Ionut Trestian Northwestern University

Extra Credit Problem 4Split

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.

Page 32: Ionut Trestian Northwestern University

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?

Page 33: Ionut Trestian Northwestern University

Extra Credit Problem 5 Matrix Multiplicationfor col in range(len(A)):

# do the appropriate thing here

for row in range(len(A)):# do the appropriate thing here when row != col