# Differences

This shows you the differences between two versions of the page.

 cs190c:lab7_09 [2009/02/27 11:48]tang cs190c:lab7_09 [2009/03/01 18:03] (current) Both sides previous revision Previous revision 2009/03/01 18:03 tang solution2009/02/27 11:48 tang 2009/02/25 15:42 seh created Next revision Previous revision 2009/03/01 18:03 tang solution2009/02/27 11:48 tang 2009/02/25 15:42 seh created Line 13: Line 13: The given code for the main function lets you load a grid to test fixed cases. You can use these three files as starting points: {{cs190c:​empty.txt|}} {{cs190c:​no_perc.txt|}} {{cs190c:​x.txt|}}. The given code for the main function lets you load a grid to test fixed cases. You can use these three files as starting points: {{cs190c:​empty.txt|}} {{cs190c:​no_perc.txt|}} {{cs190c:​x.txt|}}. + + ===== Solution ===== + ​from percolation_provided import * + from visual import rate + + def vertical_percolation(input_grid,​ trace=False):​ + size = len(input_grid) + flow_grid = grid(size, -1) + + for col in xrange(size):​ + # Initialize two variables, row and flow_blocked for the while loop. + # "​row"​ simply represents the row of the grid; flow_blocked determines + # if we hit a grid cell in input_grid that does not allow flow. If we + # do, we set flow_blocked to True and the while loop will exit. + row = 0 + flow_blocked = False + while row < size and not flow_blocked:​ + if input_grid[row][col] == 0: + flow_grid[row][col] = '​*'​ + row += 1 + # Visualize the grid and pause for 0.2 seconds (1/5) + if trace: + visualize(flow_grid,​ input_grid) + rate(5) + else: + flow_blocked = True + + # If our row variable has iterated up to be the same value as the size + # of our grid, then we've percolated and can return right now. Otherwise + # we must keep looking in the other columns. + if size == row: + return flow_grid, True + + # We've exhausted all columns and nothing has returned so far, so the grid + # doesn'​t percolate. + return flow_grid, False + + if __name__ == '​__main__':​ + input_grid = readgrid(raw_input('​Enter grid filename: ')) + flow_grid, percolates = vertical_percolation(input_grid,​ True) + if percolates: + print 'The grid percolates'​ + else: + print 'The grid does not percolate'