python - Points in the circle - performance
问题描述
I'm learning python by solving CodeWars Katas. The exercise is: "Write a function that calculates the number of points in the circle". My code:
from math import sqrt
import time
start = time.time()
def points(n):
count=0
for i in range (-n,n+1):
for j in range(-n,n+1):
if abs(i)+abs(j)<=n:
count=count+1
continue
if (sqrt(i**2+j**2))<=n:
count=count+1
return count
print (points(1000))
end = time.time()
print(end - start)
It's look like execution time for this is too long (7 second for points(1000), 21 seconds for points(2000)). How to make this more efficient (get rid of loops?).
解决方案
怎么样:
def points(n):
return n * n * PI
或者这还不够“精确”。我们是否正在查看圆点,正方形像素 - 在线内部(以及该线到底在什么像素上?),..?(也许使用n-1
?)。