change all values in array after max value

Viewed 114

Is there a way to change all the values past the max value of a list to its own? For example I have the given array arranged as followed:

values = [-10,-2,0,1,3,8,10,22,18,16,12,10]

where 22 is the max value of the list. I have the following pseudocode:

max_value = max(values)
for i in range(len(values)):
    if values[i]== max_value:
        values[i+1] = max_value
        values[i +2] == max_value
        ...etc.
        break

therefore:

values = [-10,-2,0,1,3,8,10,22,22,22,22,22]
3 Answers

Try this:

import numpy as np
myvalues = np.array([-10, -2, 0, 1, 3, 8, 10, 22, 18, 16, 12, 10])
max_index = np.argmax(myvalues) 
myvalues[max_index:] =myvalues[max_index]
print(myvalues)

The result is

[-10  -2   0   1   3   8  10  22  22  22  22  22]

In case the ascending-then-descending shape of your example array is not just a coincidence but that that's always the case for you, you could just accumulate by max:

values[:] = itertools.accumulate(values, max)

reference this post: Pythonic way to find maximum value and its index in a list?

import operator
values = [-10, -2, 0, 1, 3, 8, 10, 22, 18, 16, 12, 10]
# find the maximum value and its index
index, maximum_value = max(enumerate(values), key=operator.itemgetter(1))

# replace to maximum_value after the index
for i in range(index, len(values)):
    values[i] = maximum_value
Related