This is a part of the game of life Using python 27x In order

This is a part of the \"game of life\"
Using python 2.7x
In order to get used to looping over 2d arrays of data, copy this function named diagonalize(A) into your file: def diagonalize(width, height): creates an empty board and then modifies it so that it has a diagonal strip of \"on\" cells. A = createBoard(width, height) for row in range(height): for col in range(width): if row == col: A(row)(col) = 1 else: A[row][col] = 0 return A This function, diagonalize takes in a desired width and height. It then creates an array A and sets A\'s data so that it is an array whose cells are empty except for the diagonal where row col. Try displaying the result with >>> A = diagonalize(7, 6) >>> A [[1, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 1, 0]] >>> printBoard(A) 1000000 0100000 0010000 0001000 0000100 0000010 Take a moment to note the direction the diagonal is running that indicates which way the rows of the board are being displayed: top-to-bottom, in this case. Also, this example shows that the height and width do not have to be the same -- though it\'s certainly ok if they are. innerCells(w, h) Based on the example of diagonalize, write a variation named innerCells (w, h) which returns a 2d array of all live cells - with the value of I - except for a one-cell-wide border of empty cells (with the value of 0) around the edge of the 2d array. For example, you might try >>> A = innerCells(5, 5) >>> printBoard(A) 00000 01110 01110 01110 00000

Solution

def innerCells( w, h ):
   A = [];
   for i in range(h):
       B = [];
       for j in range(w):
           if( i==0 or i==h-1 ):
               B.append(0);
           elif( j==0 or j==w-1 ):
               B.append(0);
           else:
               B.append(1);
       A.append( B );
   return A;

def printBoard(A):
   for i in range(len(A)):
       string = \'\';
       for j in range(len(A[0])):
           string = string + str(A[i][j]);
       print string;

A = innerCells(5,5);
printBoard(A);

This is a part of the \

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site