Running the same test 10,000 times with cProfile tells me that most of the damage happens in the count() function. This is my attempt at a solution to the Quadrant Queries challenge from InterviewStreet (the problem statement can be found here).
According to InterviewStreet, I passed 3/11 testcases and I ran out of CPU time. I have no way of knowing whether I was 3 for 3 and ran out of time or say, 3 for 6 and ran out of time. I don't know if my code works on all input.
Please help me optimize this code:
def reflect_x(i, j, coordinates):
for pair in xrange(i-1, j):
coordinates[pair][1] = -coordinates[pair][1]
return coordinates
def reflect_y(i, j, coordinates):
for pair in xrange(i-1, j):
coordinates[pair][0] = -coordinates[pair][0]
return coordinates
def count(i, j, coordinates):
quad_one, quad_two, quad_three, quad_four = 0, 0, 0, 0
for pair in xrange(i-1, j):
x, y = coordinates[pair][0], coordinates[pair][1]
if x >= 0 and y >= 0:
quad_one += 1
elif x < 0 and y >= 0:
quad_two += 1
elif x < 0 and y < 0:
quad_three += 1
elif x >= 0 and y < 0:
quad_four += 1
print "%d %d %d %d" % (quad_one, quad_two, quad_three, quad_four)
def reflect(coordinates, queries):
for query in queries:
if query[0] == "X":
reflect_x(query[1], query[2], coordinates)
elif query[0] == "Y":
reflect_y(query[1], query[2], coordinates)
elif query[0] == "C":
count(query[1], query[2], coordinates)
else:
print query
if __name__ == "__main__":
N = int(raw_input())
coordinates = [[int(pair[0]), int(pair[1])] for pair in (pair.split() for pair in (raw_input() for i in xrange(N)))]
Q = int(raw_input())
queries = [[query[0], int(query[1]), int(query[2])] for query in (query.split() for query in (raw_input() for i in xrange(Q)))]
reflect(coordinates, queries)