Rewrite hit_target() function
Existing hit_target() function uses a primitive algorithm to get the target coordinates. Your task is to rewrite hit_target() function with the most optimal algorithm to make as few shots as possible to hit the target. The function should return the correct target coordinates once the target is shot. For simplicity the target coordinates are positive integers randomly selected with each execution. In your function you need to use t.distance() method, but every time you call the method it counts your shots. You function should use the minimum number shots to hit the target.
Correct solution hits the target with 5 shots or less.
class Target():
# some methods to generate a target with random coordinates
# this method returns a distance to the generated target from the shot coordinates
def distance(self,shot_x,shot_y):
self.shot_x = shot_x
self.shot_y = shot_y
self.shots += 1
print "Shot %s in (%s,%s) missed %s" % (self.shots,shot_x,shot_y,self.distance_to_target())
return self.distance_to_target()
# ------- optimize function implementation -----
def hit_target():
x,y = 0,0
while t.distance(x,y) > t.distance(x+1,y):
x += 1
while t.distance(x,y) > t.distance(x,y+1):
y += 1
return x,y
if __name__ == '__main__':
t = Target() # target created with random coordinates
print "Target coordinates: %s,%s" % hit_target()
Current output
Shot 1 in (0,0) missed 3.60555127546
Shot 2 in (1,0) missed 3.16227766017
Shot 3 in (1,0) missed 3.16227766017
Shot 4 in (2,0) missed 3.0
Shot 5 in (2,0) missed 3.0
Shot 6 in (3,0) missed 3.16227766017
Shot 7 in (2,0) missed 3.0
Shot 8 in (2,1) missed 2.0
Shot 9 in (2,1) missed 2.0
Shot 10 in (2,2) missed 1.0
Shot 11 in (2,2) missed 1.0
Shot 12 in (2,3) missed 0.0
Shot 13 in (2,3) missed 0.0
Shot 14 in (2,4) missed 1.0
Target coordinates: 2,3
0 Answer(s)