Home > Software design >  Replace With Next Largest Number
Replace With Next Largest Number

Time:05-21

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]


[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]

CodePudding user response:

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]
  • Related