EECS 110: Lec 12: Mutable Data Aleksandar Kuzmanovic Northwestern University

Slides:



Advertisements
Similar presentations
IST380 Loops got you going in circles? Nest them!
Advertisements

EXAMPLES (Arrays). Example Many engineering and scientific applications represent data as a 2-dimensional grid of values; say brightness of pixels in.
EECS 110: Lec 14: Classes and Objects Aleksandar Kuzmanovic Northwestern University
Composition CMSC 202. Code Reuse Effective software development relies on reusing existing code. Code reuse must be more than just copying code and changing.
EECS 110: Lec 11: Indefinite Loops and Program Design Aleksandar Kuzmanovic Northwestern University
1 The Game of Life Supplement 2. 2 Background The Game of Life was devised by the British mathematician John Horton Conway in More sophisticated.
Computer Science 1620 Multi-Dimensional Arrays. we used arrays to store a set of data of the same type e.g. store the assignment grades for a particular.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 8 Multidimensional.
R-1 University of Washington Computer Programming I Lecture 17: Multidimensional Arrays © 2000 UW CSE.
CS305j Introduction to Computing Two Dimensional Arrays 1 Topic 22 Two Dimensional Arrays "Computer Science is a science of abstraction -creating the right.
Games and Simulations O-O Programming in Java The Walker School
IS 313 Today What's ahead? I see I'm not the only one loopy around here… 10/7 Lec 5 ~ today, now! HMC standings!? 10/8 homework 3 due 10/14 Lec 6 ~ "dictionaries"
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 FEBRUARY 2011 Lists in Python. Introduction to Lists Lists (aka arrays): an ordered set of elements  A compound data type, like strings.
Handling Lists F. Duveau 16/12/11 Chapter 9.2. Objectives of the session: Tools: Everything will be done with the Python interpreter in the Terminal Learning.
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 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.
EECS 110: Lec 17: Review for the Final Exam 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.
Topic 26 Two Dimensional Arrays "Computer Science is a science of abstraction -creating the right model for a problem and devising the appropriate mechanizable.
1 Data Structures CSCI 132, Spring 2014 Lecture 4 Implementing Life.
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.
EECS 110: Lec 3: Data Aleksandar Kuzmanovic Northwestern University
Homework 9 Due ( M & T sections ) ( W & Th sections ) at midnight Sun., 11/3 Mon., 11/4 Problems
© Copyright 2013 by Pearson Education, Inc. All Rights Reserved. 1 Chapter 8 Multidimensional Arrays.
EECS 110: Lec 11: Indefinite Loops and Program Design Aleksandar Kuzmanovic Northwestern University
Data Collections: Lists CSC 161: The Art of Programming Prof. Henry Kautz 11/2/2009.
Two-Dimensional Arrays That’s 2-D Arrays Girls & Boys! One-Dimensional Arrays on Steroids!
Comprehending List Comprehensions
Research Topics in Computational Science. Agenda Survey Overview.
EECS 110: Lec 8: Lists of Lists Aleksandar Kuzmanovic Northwestern University
Homework due Test the random number generator Create a 1D array of n ints Fill the array with random numbers between 0 and 100 Compute and report the average.
EECS 110: Lec 10: Definite Loops and User Input Aleksandar Kuzmanovic Northwestern University
EECS 110: Lec 3: Data Aleksandar Kuzmanovic Northwestern University
1 Arrays of Arrays An array can represent a collection of any type of object - including other arrays! The world is filled with examples Monthly magazine:
Ionut Trestian Northwestern University
EECS 110: Lec 17: Review for the Final Exam Aleksandar Kuzmanovic Northwestern University
EECS 110: Lec 7: Program Planning Aleksandar Kuzmanovic Northwestern University
Scope, Aliasing, Tuples & Mutability Intro2CS – week 4a 1.
EECS 110: Lec 9: Review for the Midterm Exam Aleksandar Kuzmanovic Northwestern University
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Student Grades Application Introducing Two-Dimensional Arrays and RadioButton.
Week 9 - Wednesday.  What did we talk about last time?  2D arrays  Queen attacking pawn example  Started Game of Life.
Week 10 - Wednesday.  What did we talk about last time?  Method example  Roulette simulation  Types in Java.
EECS 110: Lec 12: Mutable Data Aleksandar Kuzmanovic Northwestern University
Arrays So far we have been dealing with single data items What if you want to handle multiple related data items of the same type? An array is a container.
Programming for Art: Arrays – 2D ART 315 Dr. J. R. Parker Art/Digital Media Lab Lec 16 Fall 2010.
Programming in C Arrays, Structs and Strings. 7/28/092 Arrays An array is a collection of individual data elements that is:An array is a collection of.
EECS 110: Lec 3: Data Aleksandar Kuzmanovic Northwestern University
EECS 110: Lec 13: Dictionaries Aleksandar Kuzmanovic Northwestern University
Announcements Assignment 2 Out Today Quiz today - so I need to shut up at 4:25 1.
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.
1 Multidimensional Arrays Chapter 13 2 The plural of mongoose starts with a "p" Initializing a multidimensional array Processing by.
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
Practical Session 9 Computer Architecture and Assembly Language.
EECS 110: Lec 10: Definite Loops and User Input
EECS 110: Lec 12: Mutable Data
EECS 110: Lec 17: Review for the Final Exam
Aleksandar Kuzmanovic Northwestern University
EECS 110: Lec 11: Indefinite Loops and Program Design
CMSC201 Computer Science I for Majors Lecture 12 – Lists (cont)
More Loop Examples Functions and Parameters
EECS 110: Lec 10: Definite Loops and User Input
HMC’s Galileo Auditorium Some of Cope’s generated MP3s:
Ionut Trestian Northwestern University
2D Array and Matrix.
Northwestern University
Functions continued.
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:

EECS 110: Lec 12: Mutable Data Aleksandar Kuzmanovic Northwestern University

>>> diff([7, 0, 6, 4]) 1 "Quiz" Print a list of strings with the specified format def diff( L ): Return the min difference between any 2 elements in L You need determine each element's index… Example: You can assume at least 2 elements in the list Only consider unsigned differences. >>> items = [“coke”, “pepsi”, “sprite”] >>> printItems(items) 0 : coke 1 : pepsi 2 : sprite def printItems( items ): Name(s):_______________________________ Hint: use a NESTED loop

"Quiz" part 1: Print Items >>> items = [“coke”, “pepsi”, “sprite”] >>> printItems(items) 0 : coke 1 : pepsi 2 : sprite

"Quiz" part 1: Print Items >>> items = [“coke”, “pepsi”, “sprite”] >>> printItems(items) 0 : coke 1 : pepsi 2 : sprite def printItems(items): for x in range(len(items)): print(x,”:”,items[x])

"Quiz" part 1: Print Items >>> items = [“coke”, “pepsi”, “sprite”] >>> printItems(items) 0:coke 1:pepsi 2:sprite def printItems(items): for x in range(len(items)): print(str(x)+”:”+items[x])

>>> diff([7, 0, 6, 4]) 1 "Quiz" Part 2 def diff( L ): Return the min difference between any 2 elements in L Example: You can assume at least 2 elements in the list Only consider unsigned differences. Hint: use a NESTED loop

>>> diff([7, 0, 6, 4]) 1 "Quiz" Part 2 def diff( L ): mindif = abs(L[1] – L[0]) for i in range(len(L)-1): for j in range(i+1,len(L)): d = abs(L[i]-L[j]) if d < mindiff: mindiff = d return mindif Return the min difference between any 2 elements in L Example: You can assume at least 2 elements in the list Only consider unsigned differences. Hint: use a NESTED loop

EECS 110 Today infinitely nested structure… HW 5 Preview: Pr 1 (Lab): The Game of Life Pr 2: Markov Text Generation required optional Pr 3: ASCII Art Pr 4: A program that reads Pr 5: Gaussian Elimination

Mutable vs. Immutable data Changeable types: dictionary Unchangeable types: list tuple string int float bool

Functions and (immutable) Variables def fact(a): result = 1 while a > 0: result *= a a -= 1 return result >>> x = 5 >>> y = fact(x) >>> x ??

Functions and (immutable) Variables def fact(a): result = 1 while a > 0: result *= a a -= 1 return result >>> x = 5 >>> y = fact(x) >>> x 5

Functions and (immutable) Variables def swap(a, b): temp = a a = b b = temp >>> x = 5 >>> y = 10 >>> swap(x, y) >>> print(x, y) ?? x y a b temp

Functions and (immutable) Variables def swap(a, b): temp = a a = b b = temp >>> x = 5 >>> y = 10 >>> swap(x, y) >>> print(x, y) 5, 10 x y a b temp

Functions and Mutable Types def swap(L, i1, i2): temp = L[i1] L[i1] = L[i2] L[i2] = temp >>> MyL = [2, 3, 4, 1] >>> swap(myL, 0, 3) >>> print(myL) ?? RAM MyL L i1 i

Functions and Mutable Types def swap(L, i1, i2): temp = L[i1] L[i1] = L[i2] L[i2] = temp >>> MyL = [2, 3, 4, 1] >>> swap(myL, 0, 3) >>> print(myL) [1,3,4,2] RAM MyL L i1 i

Reference vs. Value Mutable types: dictionary Unmutable types: list tuple string int float bool L L[0]L[1]L[2] Reference, Pointer, id L = [5,42,'hi'] L 5 42 'hi' 42 L = 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)

More examples def zeroOdd1( L ): for i in range(len(L)): if L[i] % 2 == 1: L[i] = 0 def zeroOdd2( L ): for i in L: if i % 2 == 1: i = 0 >>> L = [1, 2, 3, 4, 5] >>> zeroOdd1(L) >>> L ?? >>> L = [1, 2, 3, 4, 5] >>> zeroOdd2(L) >>> L

More examples def zeroOdd1( L ): for i in range(len(L)): if L[i] % 2 == 1: L[i] = 0 def zeroOdd2( L ): for i in L: if i % 2 == 1: i = 0 >>> L = [1, 2, 3, 4, 5] >>> zeroOdd1(L) >>> L [0,2,0,4,0] >>> L = [1, 2, 3, 4, 5] >>> zeroOdd2(L) >>> L ??

More examples def zeroOdd1( L ): for i in range(len(L)): if L[i] % 2 == 1: L[i] = 0 def zeroOdd2( L ): for i in L: if i % 2 == 1: i = 0 >>> L = [1, 2, 3, 4, 5] >>> zeroOdd1(L) >>> L [0,2,0,4,0] >>> L = [1, 2, 3, 4, 5] >>> zeroOdd2(L) >>> L [1,2,3,4,5]

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

Lists’ 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 5

Rectangular arrays Handling 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 ? A[2][3] A[0][0]

Rectangular arrays Handling 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 ? A[2][3] A[0][0] len(A)

Rectangular arrays Handling 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 ? A[2][3] A[0][0] len(A) len(A[0])

Which one works? How could we create a rectangular array (of default data, 0 ), given its height and width ? or A = [ [0]*width ]*height A = [ [0]*height ]*width

Which one works? How could we create a rectangular array (of default data, 0 ), given its height and width ? A = [ [0]*width ]*height A = [ [0]*height ]*width

What's really going on? A = [ [0]*width ]*height inner = [0]*width A = [inner]*height

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 ):

Creating a 2d array def create2dArray( width, height ): """ does just that """ A = [] # start with nothing for row in range( height ): A = A + [[]] for col in range( width ): A[row] = A[row] + [0] return A

"Quiz" What are the values of A, B, C and D at the indicated points? def mystery1(L1, L2): S = L1 for i in range(len(L2)): S[i] += L2[i] return L2 def mystery2(L1, L2): S = [0]*len(L1) for i in range(len(L2)): S[i] = L1[i] + L2[i] >>> A = [22, 10, 30] >>> B = [20, 32, 12] >>> C = [] >>> D = [] >>> C = mystery1(A, B) >>> D = mystery2(A, B) ) 2) 3) Name(s)__________________________________

"Quiz" def mystery1(L1, L2): S = L1 for i in range(len(L2)): S[i] += L2[i] return L2 def mystery2(L1, L2): S = [0]*len(L1) for i in range(len(L2)): S[i] = L1[i] + L2[i] >>> A = [22, 10, 30] >>> B = [20, 32, 12] >>> C = [] >>> D = [] >>> C = mystery1(A, B) >>> D = mystery2(A, B) ) 2) 3) Name(s)__________________________________ A: [22, 10, 30] B: [20, 32, 12] C: [] D: [] What are the values of A, B, C and D at the indicated points?

"Quiz" def mystery1(L1, L2): S = L1 for i in range(len(L2)): S[i] += L2[i] return L2 def mystery2(L1, L2): S = [0]*len(L1) for i in range(len(L2)): S[i] = L1[i] + L2[i] >>> A = [22, 10, 30] >>> B = [20, 32, 12] >>> C = [] >>> D = [] >>> C = mystery1(A, B) >>> D = mystery2(A, B) ) 2) 3) Name(s)__________________________________ A: [22, 10, 30] B: [20, 32, 12] C: [] D: [] A: [22, 10, 30] B: [20, 32, 12] C: [20, 32, 12] D: [] What are the values of A, B, C and D at the indicated points?

"Quiz" def mystery1(L1, L2): S = L1 for i in range(len(L2)): S[i] += L2[i] return L2 def mystery2(L1, L2): S = [0]*len(L1) for i in range(len(L2)): S[i] = L1[i] + L2[i] >>> A = [22, 10, 30] >>> B = [20, 32, 12] >>> C = [] >>> D = [] >>> C = mystery1(A, B) >>> D = mystery2(A, B) ) 2) 3) Name(s)__________________________________ A: [22, 10, 30] B: [20, 32, 12] C: [] D: [] A: [22, 10, 30] B: [20, 32, 12] C: [20, 32, 12] D: [] A: [22, 10, 30] B: [20, 32, 12] C: [20, 32, 12] D: None What are the values of A, B, C and D at the indicated points?

+= mutates Mutable Data (lists) WARNING: For mutable data types, the following are NOT the same A = [] B = A A += [42, 42] A = [] B = A A = A + [42, 42] NOT THE SAME! MUTATES A (B changes too) COPIES A (B does not change)

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” 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 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 an existing cell alive Any other number of neighbors kill the central cell (or keep it dead)

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 an existing cell alive Any other number of neighbors kill the central cell (or keep it dead)

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 an existing cell alive Any other number of neighbors kill the central cell (or keep it dead) life out there... Keep going!

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

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

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 old generation or "board" new generation or "board" life out there... updateNextLife(oldB, newB)

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 Why not just have update RETURN a new list? (i.e., why bother with mutation at all?) Update MUTATES the list B

Problem 1 -- 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 1 -- 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? Are all feasible configurations reachable?

See you in Lab!