1

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
  • @systempuntoout what's wrong ? Isn't an array ? Commented Oct 9, 2010 at 21:48
  • In Python you should call that data structure a list ; there are other modules that provide array objects ( array and numpy) Commented Oct 9, 2010 at 22:01

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.