Invasion Percolation: Assembly Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See

Slides:



Advertisements
Similar presentations
Introduction Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See
Advertisements

Variables Conditionals Loops The concept of Iteration Two types of loops: While For When do we use them? Iteration in the context of computer graphics.
Introduction to Computing Science and Programming I
Six compound procedures and higher-order procedures.
Python November 18, Unit 7. So Far We can get user input We can create variables We can convert values from one type to another using functions We can.
CIT 590 Unit testing. Agenda Debugging attempt 2 (because I am stubborn) What is unit testing Why? Unit testing framework in Python.
Python Programming, 2/e1 Python Programming: An Introduction to Computer Science Chapter 3 Computing with Numbers.
Working with Numbers in Alice - Converting to integers and to strings - Rounding numbers. - Truncating Numbers Samantha Huerta under the direction of Professor.
Steganography Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See
Functions Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See
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.
Program Design CMSC 201. Motivation We’ve talked a lot about certain ‘good habits’ we’d like you guys to get in while writing code. There are two main.
Fixtures Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See
COMPSCI 101 Principles of Programming Lecture 28 – Docstrings & Doctests.
Errors And How to Handle Them. GIGO There is a saying in computer science: “Garbage in, garbage out.” Is this true, or is it just an excuse for bad programming?
CIT 590 Intro to Programming Lecture 4. Agenda Doubts from HW1 and HW2 Main function Break, quit, exit Function argument names, scope What is modularity!
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.
Chapter 24 Exception CSC1310 Fall Exceptions Exceptions Exceptions are events that can modify the flow or control through a program. They are automatically.
Current Assignments Homework 2 is available and is due in three days (June 19th). Project 1 due in 6 days (June 23 rd ) Write a binomial root solver using.
Libraries Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
CSC 110 Using Python [Reading: chapter 1] CSC 110 B 1.
Winpdb—A Platform Independent Python Debugger
…and how to do stuff with them Copyright © The University of Southampton 2011 This work is licensed under the Creative Commons Attribution License See.
Storage Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See
CSE 351 GDB Introduction. Lab 1 Status? How is Lab 1 going? I’ll be available at the end of class to answer questions There are office hours later today.
First-Class Functions Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See
1. FINISHING FUNCTIONS 2. INTRODUCING PLOTTING 1.
Repetition. Loops Allows the same set of instructions to be used over and over again Starts with the keyword loop and ends with end loop. This will create.
Lists Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See
11. EXCEPTION HANDLING Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)
Invasion Percolation: Randomness Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See
Python Basics  Functions  Loops  Recursion. Built-in functions >>> type (32) >>> int(‘32’) 32  From math >>>import math >>> degrees = 45 >>> radians.
Exceptions Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See
CSE 143 Lecture 13 Recursive Backtracking slides created by Ethan Apter
ARM-7 Assembly: Example Programs 1 CSE 2312 Computer Organization and Assembly Language Programming Vassilis Athitsos University of Texas at Arlington.
Dictionaries Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See
Counting Stars Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See
While loops. Iteration We’ve seen many places where repetition is necessary in a problem. We’ve been using the for loop for that purpose For loops are.
Python Documentation Fran Fitzpatrick. Overview  Comments  Documentation Strings  Pydoc  Comments  Documentation Strings  Pydoc.
Today… Python Keywords. Iteration (or “Loops”!) Winter 2016CISC101 - Prof. McLeod1.
Today… Strings: –String Methods Demo. Raising Exceptions. os Module Winter 2016CISC101 - Prof. McLeod1.
Today… Modularity, or Writing Functions. Winter 2016CISC101 - Prof. McLeod1.
EXCEPTIONS. Catching exceptions Whenever a runtime error occurs, it create an exception object. The program stops running at this point and Python prints.
Functions with Arguments and Return Values, Oh My! CS303E: Elements of Computers and Programming.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Chapter 6 Functions The Tic-Tac-Toe Game. Chapter Content In this chapter you will learn to do the following: 0 Write your own functions 0 Accept values.
Functions. What is a Function?  We have already used a few functions. Can you give some examples?  Some functions take a comma-separated list of arguments.
Python Aliasing Copyright © Software Carpentry 2010
Program Design Invasion Percolation: Aliasing
CS170 – Week 1 Lecture 3: Foundation Ismail abumuhfouz.
Program Design Invasion Percolation: Testing
Sets and Dictionaries Examples Copyright © Software Carpentry 2010
What to do when a test fails
Testing and Debugging.
Program Design Invasion Percolation: Resolving Ties
Program Design Invasion Percolation: Neighbors
Writing Functions( ) (Part 5)
Building Java Programs
Building Java Programs
Building Java Programs
CS 1111 Introduction to Programming Fall 2018
Building Java Programs
Python programming exercise
Program Design Invasion Percolation: Bugs
Program Design Invasion Percolation: The Grid
Building Java Programs
CSE 1020:Software Development
Random numbers What does it mean for a number to be random?
Presentation transcript:

Invasion Percolation: Assembly Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See for more information. Program Design

Invasion PercolationAssembly We now know how to:

Program DesignInvasion PercolationAssembly We now know how to: - create a grid

Program DesignInvasion PercolationAssembly We now know how to: - create a grid - fill it with random numbers

Program DesignInvasion PercolationAssembly We now know how to: - create a grid - fill it with random numbers - mark cells that have been filled

Program DesignInvasion PercolationAssembly We now know how to: - create a grid - fill it with random numbers - mark cells that have been filled - find cells that might be filled next

Program DesignInvasion PercolationAssembly We now know how to: - create a grid - fill it with random numbers - mark cells that have been filled - find cells that might be filled next - choose one of them at random

Program DesignInvasion PercolationAssembly We now know how to: - create a grid - fill it with random numbers - mark cells that have been filled - find cells that might be filled next - choose one of them at random It’s time to put everything together

Program DesignInvasion PercolationAssembly We will show things in exactly the order that we would write them

Program DesignInvasion PercolationAssembly We will show things in exactly the order that we would write them Start at the top and work down...

Program DesignInvasion PercolationAssembly We will show things in exactly the order that we would write them Start at the top and work down......introducing functions and variables as we need them...

Program DesignInvasion PercolationAssembly We will show things in exactly the order that we would write them Start at the top and work down......introducing functions and variables as we need them......and tidying up a bit along the way

Program DesignInvasion PercolationAssembly '''Invasion percolation simulation. usage: invperc.py grid_size value_range random_seed ''' import sys, random # Main driver. if __name__ == '__main__': # Get parameters from command line. # Run simulation. # Report results.

Program DesignInvasion PercolationAssembly '''Invasion percolation simulation. usage: invperc.py grid_size value_range random_seed ''' import sys, random # Main driver. if __name__ == '__main__': # Get parameters from command line. # Run simulation. # Report result. Import the whole module instead of just the functions we are going to use.

Program DesignInvasion PercolationAssembly # Get parameters from the command line. arguments = sys.argv[1:] try: grid_size = int(arguments[0]) value_range = int(arguments[1]) random_seed = int(arguments[2]) except IndexError: fail('Expected 3 arguments, got %d' % \ len(arguments)) except ValueError: fail('Expected int arguments, got %s' % \ str(arguments))

Program DesignInvasion PercolationAssembly # Get parameters from the command line. arguments = sys.argv[1:] try: grid_size = int(arguments[0]) value_range = int(arguments[1]) random_seed = int(arguments[2]) except IndexError: fail('Expected 3 arguments, got %d' % \ len(arguments)) except ValueError: fail('Expected int arguments, got %s' % \ str(arguments)) Now we write this function...

Program DesignInvasion PercolationAssembly def fail(msg): '''Print error message and halt program.''' print >> sys.stderr, msg sys.exit(1)

Program DesignInvasion PercolationAssembly def fail(msg): '''Print error message and halt program.''' print >> sys.stderr, msg sys.exit(1) "doc string" def fail(...): if __name__ == '__main__'

Program DesignInvasion PercolationAssembly # Run simulation. random.seed(random_seed) grid = create_random_grid(grid_size, value_range) mark_filled(grid, grid_size/2, grid_size/2) fill_grid(grid)

Program DesignInvasion PercolationAssembly # Run simulation. random.seed(random_seed) grid = create_random_grid(grid_size, value_range) mark_filled(grid, grid_size/2, grid_size/2) fill_grid(grid) Three more functions to write...

Program DesignInvasion PercolationAssembly # Report results.

Program DesignInvasion PercolationAssembly # Report results. We haven't actually decided what to do.

Program DesignInvasion PercolationAssembly # Report results. We haven't actually decided what to do. For now, let's just count the number of filled cells.

Program DesignInvasion PercolationAssembly # Run simulation. random.seed(random_seed) grid = create_random_grid(grid_size, value_range) mark_filled(grid, grid_size/2, grid_size/2) # Report results. num_filled_cells = fill_grid(grid) + 1 print '%d cells filled' % num_filled_cells

Program DesignInvasion PercolationAssembly # Run simulation. random.seed(random_seed) grid = create_random_grid(grid_size, value_range) mark_filled(grid, grid_size/2, grid_size/2) # Report results. num_filled_cells = fill_grid(grid) + 1 print '%d cells filled' % num_filled_cells Because we filled one cell on the previous line to get things started

Program DesignInvasion PercolationAssembly def create_random_grid(N, Z): assert N > 0, 'Grid size must be positive' assert N%2 == 1, 'Grid size must be odd' assert Z > 0, 'Random range must be positive' grid = [] for x in range(N): grid.append([]) for y in range(N): grid[-1].append(random.randint(1, Z)) return grid

Program DesignInvasion PercolationAssembly def create_random_grid(N, Z): assert N > 0, 'Grid size must be positive' assert N%2 == 1, 'Grid size must be odd' assert Z > 0, 'Random range must be positive' grid = [] for x in range(N): grid.append([]) for y in range(N): grid[-1].append(random.randint(1, Z)) return grid A little documentation would help...

Program DesignInvasion PercolationAssembly def create_random_grid(N, Z): '''Return an NxN grid of random values in 1..Z. Assumes the RNG has already been seeded.''' assert N > 0, 'Grid size must be positive' assert N%2 == 1, 'Grid size must be odd' assert Z > 0, 'Random range must be positive' grid = [] for x in range(N): grid.append([]) for y in range(N): grid[-1].append(random.randint(1, Z)) return grid

Program DesignInvasion PercolationAssembly def create_random_grid(N, Z): '''Return an NxN grid of random values in 1..Z. Assumes the RNG has already been seeded.''' assert N > 0, 'Grid size must be positive' assert N%2 == 1, 'Grid size must be odd' assert Z > 0, 'Random range must be positive' grid = [] for x in range(N): grid.append([]) for y in range(N): grid[-1].append(random.randint(1, Z)) return grid "doc string" def fail(...): def create_random_grid(...): if __name__ == '__main__'

Program DesignInvasion PercolationAssembly def mark_filled(grid, x, y): '''Mark a grid cell as filled.''' assert 0 <= x < len(grid), \ 'X coordinate out of range (%d vs %d)' % \ (x, len(grid)) assert 0 <= y < len(grid), \ 'Y coordinate out of range (%d vs %d)' % \ (y, len(grid)) grid[x][y] = -1

Program DesignInvasion PercolationAssembly def mark_filled(grid, x, y): '''Mark a grid cell as filled.''' assert 0 <= x < len(grid), \ 'X coordinate out of range (%d vs %d)' % \ (x, len(grid)) assert 0 <= y < len(grid), \ 'Y coordinate out of range (%d vs %d)' % \ (y, len(grid)) grid[x][y] = -1 Will people understand this?

Program DesignInvasion PercolationAssembly FILLED = -1...other functions... def mark_filled(grid, x, y):...body of function... grid[x][y] = FILLED

Program DesignInvasion PercolationAssembly FILLED = -1...other functions... def mark_filled(grid, x, y):...body of function... grid[x][y] = FILLED "doc string" FILLED = -1 def fail(...): def mark_filled(...): def create_random_grid(...): if __name__ == '__main__'

Program DesignInvasion PercolationAssembly def fill_grid(grid): '''Fill an NxN grid until filled region hits boundary. Assumes center cell filled before call.''' N, num_filled = len(grid), 0 while True: candidates = find_candidates(grid) assert candidates, 'No fillable cells found!' x, y = random.choice(list(candidates)) mark_filled(grid, x, y) num_filled += 1 if x in (0, N-1) or y in (0, N-1): break return num_filled

Program DesignInvasion PercolationAssembly def fill_grid(grid): '''Fill an NxN grid until filled region hits boundary. Assumes center cell filled before call.''' N, num_filled = len(grid), 0 while True: candidates = find_candidates(grid) assert candidates, 'No fillable cells found!' x, y = random.choice(list(candidates)) mark_filled(grid, x, y) num_filled += 1 if x in (0, N-1) or y in (0, N-1): break return num_filled Squeezed onto one line to make it fit on the slide

Program DesignInvasion PercolationAssembly def fill_grid(grid): '''Fill an NxN grid until filled region hits boundary. Assumes center cell filled before call.''' N, num_filled = len(grid), 0 while True: candidates = find_candidates(grid) assert candidates, 'No fillable cells found!' x, y = random.choice(list(candidates)) mark_filled(grid, x, y) num_filled += 1 if x in (0, N-1) or y in (0, N-1): break return num_filled Almost always signals an "exit in the middle" loop

Program DesignInvasion PercolationAssembly def fill_grid(grid): '''Fill an NxN grid until filled region hits boundary. Assumes center cell filled before call.''' N, num_filled = len(grid), 0 while True: candidates = find_candidates(grid) assert candidates, 'No fillable cells found!' x, y = random.choice(list(candidates)) mark_filled(grid, x, y) num_filled += 1 if x in (0, N-1) or y in (0, N-1): break return num_filled The actual loop test and exit

Program DesignInvasion PercolationAssembly def fill_grid(grid): '''Fill an NxN grid until filled region hits boundary. Assumes center cell filled before call.''' N, num_filled = len(grid), 0 while True: candidates = find_candidates(grid) assert candidates, 'No fillable cells found!' x, y = random.choice(list(candidates)) mark_filled(grid, x, y) num_filled += 1 if x in (0, N-1) or y in (0, N-1): break return num_filled Another function for us to write

Program DesignInvasion PercolationAssembly def fill_grid(grid): '''Fill an NxN grid until filled region hits boundary. Assumes center cell filled before call.''' N, num_filled = len(grid), 0 while True: candidates = find_candidates(grid) assert candidates, 'No fillable cells found!' x, y = random.choice(list(candidates)) mark_filled(grid, x, y) num_filled += 1 if x in (0, N-1) or y in (0, N-1): break return num_filled Fail early, often, and loudly

Program DesignInvasion PercolationAssembly def fill_grid(grid): '''Fill an NxN grid until filled region hits boundary. Assumes center cell filled before call.''' N, num_filled = len(grid), 0 while True: candidates = find_candidates(grid) assert candidates, 'No fillable cells found!' x, y = random.choice(list(candidates)) mark_filled(grid, x, y) num_filled += 1 if x in (0, N-1) or y in (0, N-1): break return num_filled Fill and keep count

Program DesignInvasion PercolationAssembly def fill_grid(grid): '''Fill an NxN grid until filled region hits boundary. Assumes center cell filled before call.''' N, num_filled = len(grid), 0 while True: candidates = find_candidates(grid) assert candidates, 'No fillable cells found!' x, y = random.choice(list(candidates)) mark_filled(grid, x, y) num_filled += 1 if x in (0, N-1) or y in (0, N-1): break return num_filled Break out of the loop when we reach a boundary cell

Program DesignInvasion PercolationAssembly def fill_grid(grid): '''Fill an NxN grid until filled region hits boundary. Assumes center cell filled before call.''' N, num_filled = len(grid), 0 while True: candidates = find_candidates(grid) assert candidates, 'No fillable cells found!' x, y = random.choice(list(candidates)) mark_filled(grid, x, y) num_filled += 1 if x in (0, N-1) or y in (0, N-1): break return num_filled Report how many cells this function filled

Program DesignInvasion PercolationAssembly def fill_grid(grid): '''Fill an NxN grid until filled region hits boundary.''' N, num_filled = len(grid), 0 while True: candidates = find_candidates(grid) assert candidates, 'No fillable cells found!' x, y = random.choice(list(candidates)) mark_filled(grid, x, y) num_filled += 1 if x in (0, N-1) or y in (0, N-1): break return num_filled "doc string" FILLED = -1 def fail(...): def mark_filled(...): def fill_grid(...): def create_random_grid(...): if __name__ == '__main__'

Program DesignInvasion PercolationAssembly def find_candidates(grid): '''Find low-valued neighbor cells.''' N = len(grid) min_val = sys.maxint min_set = set() for x in range(N): for y in range(N): if (x > 0) and (grid[x-1][y] == FILLED) \ or (x < N-1) and (grid[x+1][y] == FILLED) \ or (y > 0) and (grid[x][y+1] == FILLED) \ or (y < N-1) and (grid[x][y+1] == FILLED):

Program DesignInvasion PercolationAssembly def find_candidates(grid): '''Find low-valued neighbor cells.''' N = len(grid) min_val = sys.maxint min_set = set() for x in range(N): for y in range(N): if (x > 0) and (grid[x-1][y] == FILLED) \ or (x < N-1) and (grid[x+1][y] == FILLED) \ or (y > 0) and (grid[x][y+1] == FILLED) \ or (y < N-1) and (grid[x][y+1] == FILLED): Let's stop right there.

Program DesignInvasion PercolationAssembly That's kind of hard to read. def find_candidates(grid): '''Find low-valued neighbor cells.''' N = len(grid) min_val = sys.maxint min_set = set() for x in range(N): for y in range(N): if (x > 0) and (grid[x-1][y] == FILLED) \ or (x < N-1) and (grid[x+1][y] == FILLED) \ or (y > 0) and (grid[x][y+1] == FILLED) \ or (y < N-1) and (grid[x][y+1] == FILLED):

Program DesignInvasion PercolationAssembly In fact, it contains a bug. def find_candidates(grid): '''Find low-valued neighbor cells.''' N = len(grid) min_val = sys.maxint min_set = set() for x in range(N): for y in range(N): if (x > 0) and (grid[x-1][y] == FILLED) \ or (x < N-1) and (grid[x+1][y] == FILLED) \ or (y > 0) and (grid[x][y+1] == FILLED) \ or (y < N-1) and (grid[x][y+1] == FILLED):

Program DesignInvasion PercolationAssembly Should be y-1 def find_candidates(grid): '''Find low-valued neighbor cells.''' N = len(grid) min_val = sys.maxint min_set = set() for x in range(N): for y in range(N): if (x > 0) and (grid[x-1][y] == FILLED) \ or (x < N-1) and (grid[x+1][y] == FILLED) \ or (y > 0) and (grid[x][y+1] == FILLED) \ or (y < N-1) and (grid[x][y+1] == FILLED):

Program DesignInvasion PercolationAssembly Listen to your code as you write it.

Program DesignInvasion PercolationAssembly def find_candidates(grid): '''Find low-valued neighbor cells.''' N = len(grid) min_val = sys.maxint min_set = set() for x in range(N): for y in range(N): if is_candidate(grid, x, y):

Program DesignInvasion PercolationAssembly def find_candidates(grid): '''Find low-valued neighbor cells.''' N = len(grid) min_val = sys.maxint min_set = set() for x in range(N): for y in range(N): if is_candidate(grid, x, y): Much clearer when read aloud.

Program DesignInvasion PercolationAssembly def find_candidates(grid):...loop...: if is_candidate(grid, x, y): # Has current lowest value. if grid[x][y] == min_val: min_set.add((x, y)) # New lowest value. elif grid[x][y] < min_val: min_val = grid[x][y] min_set = set([(x, y)])...

Program DesignInvasion PercolationAssembly "doc string" FILLED = -1 def fail(...): def mark_filled(...): def find_candidates(...): def fill_grid(...): def create_random_grid(...): if __name__ == '__main__' def find_candidates(grid):...loop...: if is_candidate(grid, x, y): # Has current lowest value. if grid[x][y] == min_val: min_set.add((x, y)) # New lowest value. elif grid[x][y] < min_val: min_val = grid[x][y] min_set = set([(x, y)])...

Program DesignInvasion PercolationAssembly "doc string" FILLED = -1 def fail(...): def mark_filled(...): def is_candidate(...): def find_candidates(...): def fill_grid(...): def create_random_grid(...): if __name__ == '__main__' def is_candidate(grid, x, y): '''Determine whether the cell at (x,y) is now a candidate for filling.'''...see previous episode...

Program DesignInvasion PercolationAssembly It's finally time to run our program.

Program DesignInvasion PercolationAssembly It's finally time to run our program. test

Program DesignInvasion PercolationAssembly It's finally time to run our program. Because there's a bug lurking in what we just wrote. test

Program DesignInvasion PercolationAssembly It's finally time to run our program. Because there's a bug lurking in what we just wrote. Try to find it by reading the code carefully before moving on. test

Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See for more information. May 2010 created by Greg Wilson