I have several points stored in an array. I need to find bounds of that points ie. the rectangle which bounds all the points. I know how to solve this in plain Python.
I would like to know is there a better way than the naive max, min over the array or built-in method to solve the problem.
points = [[1, 3], [2, 4], [4, 1], [3, 3], [1, 6]]
b = bounds(points) # the function I am looking for
# now b = [[1, 1], [4, 6]]
My approach to getting performance is to push things down to C level whenever possible:
By my (crude) measure, this runs about 1.5 times faster than @ReblochonMasque's
bounding_box_naive()
. And is clearly more elegant. ;-)You cannot do better than
O(n)
, because you must traverse all the points to determine themax
andmin
forx
andy
.But, you can reduce the constant factor, and traverse the list only once; however, it is unclear if that would give you a better execution time, and if it does, it would be for large collections of points.
Here is the "naive" approach: (it is the fastest of the two)
and the (maybe?) less naive:
profiling results:
size = 1,000 points
size = 10,000 points
size 100,000 points
size 1,000,000 points
Clearly, the first "not so naive" approach is faster by a factor
2.5 - 3