Find Highest/Lowest Number in an Array
Author |
Message |
Planet_Fall
|
Posted: Mon Jan 20, 2014 9:49 am Post subject: 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.
Python: |
number_comp = array[0]
# Gets Lowest Number
for i in range (1, number_info):
number_to_comp = array[i]
if number_comp > number_to_comp:
number_comp = number_to_comp
lowest_num = number_comp
print (lowest_num)
number_comp = array[0]
# Gets Highest Number
for i in range (1, number_info):
number_to_comp = array[i]
if number_comp < number_to_comp:
number_comp = number_to_comp
highest_num = number_comp
print (highest_num)
|
|
|
|
|
|
|
Sponsor Sponsor
|
|
|
Insectoid
|
Posted: Mon Jan 20, 2014 12:44 pm Post subject: 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
|
Posted: Mon Jan 20, 2014 1:19 pm Post subject: 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
|
Posted: Mon Jan 20, 2014 8:48 pm Post subject: RE:Find Highest/Lowest Number in an Array |
|
|
Because one liners are awesome.
Python: |
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
|
http://docs.python.org/2/library/functions.html#reduce
Less efficient, but also less code. |
|
|
|
|
|
Dreadnought
|
Posted: Mon Jan 20, 2014 8:57 pm Post subject: Re: Find Highest/Lowest Number in an Array |
|
|
Zren wrote:
Because one liners are awesome.
Python: |
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
|
http://docs.python.org/2/library/functions.html#reduce
Less efficient, but also less code.
If you're going to use min/max anyway why not just do this?
Python: | arr = range(10)
print arr
from random import shuffle
shuffle(arr)
print arr
print min(arr)
print max(arr) |
|
|
|
|
|
|
Zren
|
Posted: Mon Jan 20, 2014 9:12 pm Post subject: Re: Find Highest/Lowest Number in an Array |
|
|
Dreadnought @ Mon Jan 20, 2014 8:57 pm wrote:
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 |
|
|
|
|
|
|
|