D_Wills
D_Wills

Reputation: 355

how to get the maximum value from a specific portion of a array in python

I have a specific scenario that I need to scan a specific portion of an array for a maximum value of that portion and return the position of that value with regards to the entire array. for example

 searchArray = [10,20,30,40,50,60,100,80,90,110]

I want to scan for the max value in portion 3 to 8, (40,50,60,100,80,90)

and then return the location of that value.

so in this case max value is 100 and location is 6

is there a way to get that using python alone or with help oy numpy

Upvotes: 4

Views: 8255

Answers (6)

Jacques Gaudin
Jacques Gaudin

Reputation: 16958

With itemgetter:

pos = max(enumerate(searcharray[3:9], 3), key=itemgetter(1))[0]

Upvotes: 0

Jan van der Vegt
Jan van der Vegt

Reputation: 1511

First slice your list and then use index on the max function:

searchArray = [10,20,30,40,50,60,100,80,90,110]
slicedArray = searchArray[3:9]
print slicedArray.index(max(slicedArray))+3

This returns the index of the sliced array, plus the added beginSlice

Upvotes: 2

Byte Commander
Byte Commander

Reputation: 6736

Use enumerate to get an enumerated list of tuples (actually it's a generator, which means that it always only needs memory for one single entry and not for the whole list) holding the indexes and values, then use max with a custom comparator function to find the greatest value:

searchArray = [10,20,30,40,50,60,100,80,90,110]
lower_bound = 3  # the lower bound is inclusive, i.e. element 3 is the first checked one
upper_bound = 9  # the upper bound is exclusive, i.e. element 8 (9-1) is the last checked one

max_index, max_value = max(enumerate(searchArray[lower_bound:upper_bound], lower_bound),
                           key=lambda x: x[1])

print max_index, max_value
# output: 6 100

See this code running on ideone.com

Upvotes: 1

Vivek Kalyanarangan
Vivek Kalyanarangan

Reputation: 9081

Try this...Assuming you want the index of the max in the whole list -

import numpy as np

searchArray = [10,20,30,40,50,60,100,80,90,110]

start_index = 3
end_index = 8

print (np.argmax(searchArray[start_index:end_index+1]) + start_index)

Upvotes: 1

Pep_8_Guardiola
Pep_8_Guardiola

Reputation: 5252

I'd do it like this:

sliced = searchArray[3:9]
m = max(sliced)
pos = sliced.index(m) + 3

I've added an offset of 3 to the position to give you the true index in the unmodified list.

Upvotes: 0

Arun G
Arun G

Reputation: 1688

i guess this what you want

maxVal = max(searchArray[3:8]) // to get max element

position = searchArray.index(max(ary[3:8])) //to get the position of the index

Upvotes: -3

Related Questions