
-----------------------------------
Planet_Fall
Mon Jan 20, 2014 9:49 am

Find Highest/Lowest Number in an Array
-----------------------------------
Is there a command that searches an array to find the lowest/highest number?
They way I do it looks a little inefficient. 


number_comp = array

-----------------------------------
Insectoid
Mon Jan 20, 2014 12:44 pm

RE:Find Highest/Lowest Number in an Array
-----------------------------------
Without sorting, this is the most efficient method. You can, of course, halve the runtime by looking for both the lowest and highest values in the same loop.

-----------------------------------
Raknarg
Mon Jan 20, 2014 1:19 pm

RE:Find Highest/Lowest Number in an Array
-----------------------------------
This method is quite efficient. It runs in linear time (basically means you only have to go through the list once) to find your solution, which is fast. you could have 100000 elements in the list with no real difference in speed.

-----------------------------------
Zren
Mon Jan 20, 2014 8:48 pm

RE:Find Highest/Lowest Number in an Array
-----------------------------------
Because one liners are awesome.


arr = range(10)
print arr

from random import shuffle
shuffle(arr)
print arr

print reduce(min, arr)
print reduce(max, arr)


[code]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[8, 7, 2, 6, 5, 9, 4, 0, 3, 1]
0
9
[/code]

http://docs.python.org/2/library/functions.html#reduce

Less efficient, but also less code.

-----------------------------------
Dreadnought
Mon Jan 20, 2014 8:57 pm

Re: Find Highest/Lowest Number in an Array
-----------------------------------

Because one liners are awesome.


arr = range(10)
print arr

from random import shuffle
shuffle(arr)
print arr

print reduce(min, arr)
print reduce(max, arr)




If you're going to use min/max anyway why not just do this?
arr = range(10) 
print arr 

from random import shuffle 
shuffle(arr) 
print arr 

print min(arr)
print max(arr)

-----------------------------------
Zren
Mon Jan 20, 2014 9:12 pm

Re: Find Highest/Lowest Number in an Array
-----------------------------------

If you're going to use min/max anyway why not just do this?


Because I've never read the docs for min/max. xD Never realized it accepted iterables.

For anyone interested in the source code of the built in min/max functions: http://hg.python.org/cpython/file/0bcf1669912a/Python/bltinmodule.c#l1348
