def positionMax(sequence, excludedIndexesSet=None):
if not badindexes:
return max( izip(sequence, xrange(len(sequence)) ) )[1]
else:
badindexes = set(badindexes)
return max( (e,i) for i,e in enumerate(sequence) if i not in badindexes )[1]
SwiftCodersays:
You should also try a functional idiom – typically better and faster:
array = [1.0, 2.0, 3.0, 1.0]
m = reduce(max, array)
Protector onesays:
I’m sorry SwiftCoder, but I believe that is a max. It is equivalent to:
m = max(array)
My (arg)max:
lambda array: max([array[i],i] for i in range(len(array)))[1]
In case of duplicate values you solution returns the last position, while the array.index(max(array)) solution returns the first which, beside the simplicity of the solution, seems to be the more natural answer.
You can try this:
def positionMax(sequence, excludedIndexesSet=None):
if not badindexes:
return max( izip(sequence, xrange(len(sequence)) ) )[1]
else:
badindexes = set(badindexes)
return max( (e,i) for i,e in enumerate(sequence) if i not in badindexes )[1]
You should also try a functional idiom – typically better and faster:
array = [1.0, 2.0, 3.0, 1.0]
m = reduce(max, array)
I’m sorry SwiftCoder, but I believe that is a max. It is equivalent to:
m = max(array)
My (arg)max:
lambda array: max([array[i],i] for i in range(len(array)))[1]
Cheers!
array.index(max(array))
is it too simple?
import numpy
array = numpy.array ( [1,2,4,3,5,1 ] )
numpy.argmax( array )
# should return 4
In case of duplicate values you solution returns the last position, while the array.index(max(array)) solution returns the first which, beside the simplicity of the solution, seems to be the more natural answer.
How about
max(xrange(len(array)), key=array.__getitem__)
great, much faster!
numpy.ndarray object has no attributes index and maxarg. What should I do?
argmax=max([(i[0], array[i[0]]) \
for i in enumerate(array)], key=lambda t:t[1])[0]