tags:

views:

58

answers:

2

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

+2  A: 

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.)

aaronasterling
the same idea with tuple unpacking: topleft, topright, bottomleft, bottomright = sorted(vertices)
tokland
@tokland, good idea. I was just getting the point across I guess. That's probably how i'd actually write it.
aaronasterling
A: 
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)
Richard Fearn