I have solved one problem on Codeforces and I guess the output is quite correct. However, it is slow for input in range of thousands. Since, I am learning Python now, it would be great help if one could help me optimise this code. Any notes, tips or suggestions on the sidelines are always welcome.
The question is a practice question and hence does not violate any contest rules.
import sys
import time
_no_of_ants, _no_of_queries = (input().split())
no_of_ants = int(_no_of_ants)
no_of_queries = int(_no_of_queries)
class ants_cord():
def __init__(self,point,no_of_ants):
self.co_ant = {point:no_of_ants}
def ants_at_point(self,point):
return self.co_ant[point]
def move_ants(self,point):
x1,y1 = point
if (x1+1,y1) in self.co_ant.keys():
self.co_ant[((x1+1),y1)] += 1
else:
self.co_ant[((x1+1),y1)] = 1
if (x1,y1+1) in self.co_ant.keys():
self.co_ant[((x1),y1+1)] += 1
else:
self.co_ant[((x1),y1+1)] = 1
if (x1,y1-1) in self.co_ant.keys():
self.co_ant[((x1),y1-1)] += 1
else:
self.co_ant[((x1),y1-1)] = 1
if (x1-1,y1) in self.co_ant.keys():
self.co_ant[((x1-1),y1)] += 1
else:
self.co_ant[((x1-1),y1)] = 1
self.co_ant[point] -= 4
def check_status(self):
for key in self.co_ant.keys():
if k.co_ant[key] >= 4:
return key
else: return False
start = time.time()
k = ants_cord((0,0),no_of_ants)
point = k.check_status()
while point:
k.move_ants(point)
point = k.check_status()
end = time.time()
print("Sec:{}".format(end-start))
while no_of_queries:
_x,_y = input().split()
x = int(_x)
y = int(_y)
if (x,y) in k.co_ant:
print(k.co_ant[(x,y)])
else:
print('0')
no_of_queries -= 1
EDIT: I updated the code according to suggestion. But I still get a TLE error in test case 4. Should I employ other algorithm then?