How to change numbers in a list to make it monotonically decreasing?

I have got a list:

first = [100, 110, 60]

How to make that: if the next number is greater than the previous one, then it is necessary to reduce this number like preceding number.
For example, the answer should be:

ans = [100, 100, 60]

The second example:

arr = [60,50,60]
ans = [60, 50, 50]

The third example:

arr = [20, 100, 150]
ans = [20, 20, 20]

I try to, but i think it’s not good idea

for i in range(len(arr)-1):

    if arr[i] < arr[i+1]:
        answer.append(a[i+1] - 10)
    if arr[i] < arr[i+1]:
        answer.append(a[i])
    if arr[i] < arr [i+1]:
        answer.append(arr[-1])

>Solution :

This will modify the list in situ:

def fix_list(_list):
    for i, v in enumerate(_list[1:], 1):
        _list[i] = min(v, _list[i-1])
    return _list


print(fix_list([100, 110, 60]))
print(fix_list([60, 50, 60]))
print(fix_list([20, 100, 150]))

Output:

[100, 100, 60]
[60, 50, 50]
[20, 20, 20]

Leave a Reply