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

Replace With Next Largest Number

I need to write a function that replaces each number with the next highest number in the list.

Say we have the list[5, 7, 3, 2, 8].
The 5 gets replaced by the 7 and the list becomes [7, 5, 3, 2, 8].
After that, we switch the 5 and the 8 so it becomes [7, 8, 3, 2, 5]. Eventually the max of the entire list gets replaced by -1.

By the end this example should output [7, 8, 5, 3, -1]. I wrote this code:

def replace_next_largest(lst):  
    maxes = []
    for i in range(len(lst)):
        check = lst[i]
        next_mx = [i for i in lst if i > check and not i in maxes]
        if next_mx:
            maxes.append(next_mx[0])
        else:
            if maxes.insert(lst.index(max(lst)),-1 ) 
    return maxes

but it does not work with the input [4, 1, 6, -7, -8, 2], but it works for the other list mentioned above and all the other tests. My output is [6, 4, -1, -1, 1, -7] and it should be
[6, 2, -1, 1, -7, 4]

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

[6, 4, -1, -1, 1, -7] <— My Answer

[6, 2, -1, 1, -7, 4] <— correct answer

It works with [5, 7, 3, 2, 8] , [2, 3, 4, 5], and [1, 0, -1, 8, -72]

>Solution :

Based on your desired result, you can sort the list, then do a lookup that finds pairs the numbers with the next largest. With that you can just replace the items in the list. By zipping the values as pairs, the greatest value will not have an entry. You can use this to replace it with -1 when you try to look it up.

def swap_large(l):
    s = sorted(l)
    d = {k:v for k, v in zip(s, s[1:])}
    
    return [d.get(n, -1) for n in l]

swap_large([5, 7, 3, 2, 8])
# [7, 8, 5, 3, -1]

swap_large([4, 1, 6, -7, -8, 2])
# [6, 2, -1, 1, -7, 4]
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