Find out if a point is within a circle on a Cartesian plane

Asked

Viewed 1,218 times

3

I was doing the task Target shooting of the 2013 Brazilian Computer Olympiad (OBI) at Programming level 2, which can be found here, and I was able to do it without great difficulty. The task was to figure out how many points a person would make by shooting at a target, considering that it would earn a point for each circumference that each shot was internal or belonged to. The program entry consists of the number of circles (all whose center is located in (0,0)) and their radii and the number of shots and their coordinates. The output is just the number of points one would make.

Well, so far so good - my code works. The problem is that in the official tester of OBI, which can be found here, I received many results with time limit exceeded and ended up with only 20 points of 100 possible. I wanted help, therefore, to improve the performance of my program.

Note: The order of entries cannot be changed.

#!/usr/bin/env python
# -*- coding: UTF-8 -*-

def calcula_pontos():
    qtd_circulos, qtd_tiros = raw_input().split()
    raios_circulos = [float(raw_input()) for circulo in range(int(qtd_circulos))]
    cord_tiros = [raw_input().split() for tiro in range(int(qtd_tiros))]
    pontos = 0
    for x, y in cord_tiros:
        for raio in raios_circulos:
            if((int(x) ** 2) + (int(y) ** 2) > (raio ** 2)):
                continue
            else:
                pontos += 1
    print pontos

calcula_pontos()

1 answer

1

#!/usr/bin/env python
# -*- coding: UTF-8 -*-

def calcula_pontos():

    def closure_dist2_tiro_centro():
        input = raw_input().split()
        return (int(input[0]) ** 2) + (int(input[0]) ** 2)

    qtd_circulos, qtd_tiros = raw_input().split()
    raios2_circulos = [(float(raw_input()) ** 2) for circulo in range(int(qtd_circulos))]
    dist2_tiros = [closure_dist2_tiro_centro() for tiro in range(int(qtd_tiros))]

    pontos = 0
    for tiro in dist2_tiros:
        for idx,raio in enumerate(raios2_circulos):
            if tiro < raio:
                pontos += (len(raios2_circulos) - idx)
                break
    print pontos

calcula_pontos()

The above code takes into account two optimizations:

  • Data is calculated as soon as possible, in understanding the input list
  • The second list is iterated as little as possible, considering that if a shot has less distance than the radius of one of the circles, it has it for all of the following

Browser other questions tagged

You are not signed in. Login or sign up in order to post.