Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate two maximums at the same time?

I have a list of Point objects, each of which has an x and y property. I wish to calculate the maximum_x and maximum_y, without iterating through twice. I could do this:

max_x = max(points, key=lambda p: p.x)
max_y = max(points, key=lambda p: p.y)

But of course, this will iterate twice. I could do it manually, but since finding the maximum is so simple, I fear it'll increase clutter. Is there any way to do this with the built in max function?

like image 447
naiveai Avatar asked Dec 06 '18 07:12

naiveai


2 Answers

No, not really. What you already have is the best way, just calling max twice.

Anyway, think about it like this: whether you iterate once and make two comparisons during each iteration, or you iterate twice and make one comparison during iteration, it does not make much difference in the end.

like image 82
wim Avatar answered Sep 19 '22 00:09

wim


This would be possible using numpy assuming x and y are in one two-dimensional array:

import numpy as np


points_array = np.array([(p.x,p.y) for p in points]) 
xmax, ymax = points_array.max(axis=0)

But this would mean you would have to restructure your data. That being said, if that is the only reason you need numpy, I think I would stick with the clutter.

like image 35
M.T Avatar answered Sep 20 '22 00:09

M.T