I have working code, but am wondering if there is a numpy
implementation for it. This more for satisfying my curiosity and about optimising and making code prettier; I don't have an acute problem. Still, I guess this situation is common enough to be interesting to others than just myself.
So, the situation: I'm calculating a value many times in a loop, and would like to only save the minimum and maximum value.
Initially, I used
import numpy as np
vals = []
for obj in objects:
#...do stuff...
vals.append(obj.calc_value())
#...do more stuff
minmax = [np.min(vals), np.max(vals)]
which works and is nice and short. However, because I'm storing all values, yet only need the min and max, this seems like a waste of perfectly good memory space. Therefore I changed it to
import numpy as np
minmax = [np.inf, -np.inf]
for obj in objects:
#...do stuff...
val = obj.calc_value()
if val < minmax[0]:
minmax[0] = val
if val > minmax[1]:
minmax[1] = val
#...do more stuff
which also work, but is a bit verbose. Sure, I could extract the four lines in the code into a function I guess, but...
I couldn't help but wonder, if there isn't a numpy
function for this. Something like a "reverse" clip
function. A function which, like clip
, compares a value to an interval. But which does not return the (possibly changed) value so that it lies in the provided interval (which is what clip
does), but rather returns the (possibly extended) interval that is needed so that the provided value lies in it.
import numpy as np
minmax = [np.inf, -np.inf]
for obj in objects:
#...do stuff...
minmax = np.reverse_clip(minmax, obj.calc_value())
#...do more stuff
If there is, I'd love to hear about it. Also, any ideas how I could have found it without asking here? I looked at numpy
's array methods, but couldn't find it there.