Tasha
Tasha

Reputation: 55

Finding minimum and maximum in a list of tuples i.e (min,max),(max,min)?

I have a list of tuples, (x1,y1),(x2,y2) etc and what I'd like to find is the tuple where x is a maximum and y is a minimum and various other combinations. I have been able to find where x is a maximum and y is a maximum, and when x is a minimum and y is a minimum, but I'm not sure how to first filter by maximum, then by minimum and vice versa.

Here's what I've tried so far:

coords = [(200,200),(40,150),(50,180),(20,200),(200,20),(20,20)]

c1 = max(coords, key=operator.itemgetter(0))
c2 = min(coords,key = operator.itemgetter(0))
c3 = max(coords,key = operator.itemgetter(1))
c4 = min(coords,key = operator.itemgetter(1))

#returns (200,200),(20,200),(200,200),(200,20))
#wanted (200,200),(20,200), (200, 20), (20,20) 
#(max,max), (min,max), (max,min), (min,min) or some order of this

In reality 'coords' has more than 6 tuples. I end up with the same coordinate being returned for c1 and c3 for example when I wanted coords[0] and coords[3], so (max,max) and then (min,max). Am I over-complicating things, or is there a much simpler way to solve this? The order of the output doesn't particularly matter as long as it is the same order every time the coords change. I have simplified this issue to post here so there may be some errors sorry. Thanks!

Upvotes: 0

Views: 524

Answers (1)

Dave Costa
Dave Costa

Reputation: 48121

A possible approach is to identify the maximum and minimum values of x and y, generate all possible tuples with those values, and check if those tuples exist in the list.

coords = [(200,200),(20,200),(200,20),(20,20)]
max_x = max([t[0] for t in coords])
min_x = min([t[0] for t in coords])
max_y = max([t[1] for t in coords])
min_y = min([t[1] for t in coords])

for x in [min_x,max_x]:
  for y in [min_y,max_y]:
     if (x,y) in coords:
       print( (x,y) )

Given your clarifying comments, I think that's sufficient for your needs. If the input data didn't reliably contain the combinations you're looking for, you'd have to be more specific about what you want.

For that matter, if you are guaranteed that the combinations you want are in the input data, you could remove the if line and just output all of the permutations. But it's probably wise to verify they are actually there.

Upvotes: 2

Related Questions