Search code examples
pythonlistsortinginsertion

Python sorted list insertion


I need help for an exercise in python where I have to fill a preexistent code.

The function take an integer and a sorted list, it inserts the value a and then returns the new list, I have to replace the dots by the correct answer

It looks like this :

def insert(a, tab):
    l = list(tab)
    l.append(a)
    i = ...
    while a < ... :
        l[i+1] = ...
        l[i] = a
        i = ...
    return l

>>> insert(3,[1,2,4,5])
[1, 2, 3, 4, 5]

Thanks for the help.


Solution

  • def insert(a, tab):
        l = list(tab)
        l.append(a)
        i = len(l) - 2
        while a < l[i] and i >= 0:
            l[i+1] = l[i]
            l[i] = a
            i -= 1
        return l