Third person: Given a 2-d array, write code to print it out in a snake pattern. For example, if the array is this: 1, 2, 3 4, 5, 6 7, 8, 9 the routine prints this: 1,2,3,6,9,8,7,4,5 The array is an NxN array. The final question was just how to write a connection pool (i.e, a class that returns connections to the user, and if the user is done, returns them back to the pool)
Anonymous
#!/usr/bin/python import math; # test several small sized matrices def main(): for N in range(0, 8): A = []; count = 1; for row in range(0, N): A.append([]); for col in range(0, N): A[row].append(count); count += 1; printMat(A); print snake(A); # prints the matrix in standard form def printMat(A): if len(A) == 0: print "[\t[\t]\t]"; return; print "[\t", for row in range(0, len(A)): if row == 0: print "[\t", else: print "\t[\t", for col in range(0, len(A[row])): if col == len(A[row]) - 1: if row == len(A) - 1: print str(A[row][col]) + "]\t]"; else: print str(A[row][col]) + "]"; else: print str(A[row][col]) + ",\t", # return array reading the matrix in snake fashion def snake(A): N = len(A); array = []; # outermost layer is 0 for layer in range(0, int(math.floor((N + 1) / 2))): d_u_count_range = max(4 * N - 8 * layer - 4, 0); l_r_count_range = d_u_count_range / 4; u_d_count_range = d_u_count_range / 2; r_l_count_range = 3 * l_r_count_range; for count in range(0, d_u_count_range): # append left to right values if count < l_r_count_range: array.append(A[layer][layer + count]); # append up to down values elif count < u_d_count_range: array.append(A[layer + count - l_r_count_range] [N - 1 - layer]); # append right to left values elif count < r_l_count_range: array.append(A[layer + l_r_count_range] [N - 1 - layer - (count - u_d_count_range)]); # append down to up values else: array.append(A[layer + l_r_count_range - (count - r_l_count_ran\ ge)] [layer]); # append center value if matrix had odd dimensions if N % 2 == 1: array.append(A[(N - 1) / 2][(N - 1) / 2]); return array; if __name__ == '__main__': main();
Check out your Company Bowl for anonymous work chats.