hi,
I've the following array:
[[499, 3], [502, 3], [502, 353], [499, 353]]
They are the verteces of a rectangle.
I need to find the top-left, top-right, bottom-left and bottom-right vertex.
What's the best python code to do it ?
thanks
hi,
I've the following array:
[[499, 3], [502, 3], [502, 353], [499, 353]]
They are the verteces of a rectangle.
I need to find the top-left, top-right, bottom-left and bottom-right vertex.
What's the best python code to do it ?
thanks
edit: thanks to tokand for pointing out that this can be done with tuple unpacking.
you could sort it.
(bottomleft, bottomright,topleft, topright) = sorted(vertices)
or you could do it in place with
corners.sort()
(bottomleft, bottomright,topleft, topright) = corners
# the unpacking here is redundant but demonstrative
For reference, the output of sorted is:
>>> a = [[499, 3], [502, 3], [502, 353], [499, 353]]
>>> sorted(a)
[[499, 3], [499, 353], [502, 3], [502, 353]]
>>>
This will be O(nlogn) whereas there are surely O(n) solutions available. But for a list of this size, I don't think it's a biggy unless you have a ton of them, (in which case, the speed of the native C implementation will outperform a custom python function anyways so it's still optimal from a practical perspective.)
vertices = [[499, 3], [499, 353], [502, 3], [502, 353]]
# if the origin is the top left
(topleft, bottomleft, topright, bottomright) = sorted(vertices)
# if the origin is the bottom left
(bottomleft, topleft, bottomright, topright) = sorted(vertices)