Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PYTHON - finding the maximum of every 10 integers in an array

I have a large array of integers, and I need to print the maximum of every 10 integers and its corresponding index in the array as a pair.

ex. (max_value, index of max_value in array)

I can successfully find the maximum value and the corresponding index within the first 10 integers, however I am having trouble looping through the entire array.

I have tried using:

a = some array of integers

split = [a[i:i+10] for i in xrange(0, len(a), 10)] 

for i in split:
    j = max(i) 
    k = i.index(max(i))
    print (j,k)

The issue with this method is that it splits my array into chunks of 10 so the max_values are correct, but the indexes are inaccurate (all of the indexes are between 0-10.) I need to find a way of doing this that doesn't split my array into chunks so that the original indices are retained. I'm sure there is an easier way of looping through to find max values but I can't seem to figure it out.

like image 683
nikki_c Avatar asked Nov 30 '22 15:11

nikki_c


1 Answers

A small modification to your current code:

a = some array of integers

split = [a[i:i+10] for i in xrange(0, len(a), 10)] 

for index, i in enumerate(split):
    j = max(i) 
    k = i.index(max(i))
    print (j, k+10*index)
like image 93
Harald Nordgren Avatar answered Dec 03 '22 03:12

Harald Nordgren