2

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]
  • Is it only coincidence that from the start to the max, the sequence is ascending? Or is that always the case for you? And is it always descending from the max until the end? Just like the number in your username btw... – superb rain Feb 28 '21 at 03:52
  • to clarify, the values ascend and descend at an absolute maximum . – angelesdoming1234321 Feb 28 '21 at 06:25

3 Answers3

3

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]
Frank
  • 1,151
  • 10
  • 22
2

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)
superb rain
  • 5,300
  • 2
  • 11
  • 25
0

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
Sean Hsieh
  • 305
  • 2
  • 13