Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading