-1

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.

Soomom
  • 11
  • 3

4 Answers4

1
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
rhorwitz
  • 104
  • 2
  • 1
    As far as I can tell, this will crash if the element has to be inserted at the beginning of the list. However, checking `i` in the loop condition to avoid that problem does not seem possible with the original code. – Luka Mesaric Jan 28 '21 at 16:22
  • Good catch. Updated to fix – rhorwitz Jan 28 '21 at 16:47
  • Nice fix. For anyone wondering, by having `i>=0` after `a < l[i]`, `l[-1]` will be accessed in the last iteration. In Python that is not a problem, but in other languages it might cause an error. `i>=0` should be checked first, but the provided code template does not allow doing that. That is probably an oversight. – Luka Mesaric Jan 29 '21 at 17:15
0

Disclaimer - Nothing new here. Just for a reference, make the variable more descriptive and simplify the code. (for future reading, or myself)

def insert(x, lst):
    ''' lst is a sorted list'''
    ''' bubble sort - '''
    
    lst.append(x)   # to the end
    
    i = len(lst) - 2
    
    while i >=0 and lst[i] > x:
        lst[i+1], lst[i] = lst[i], x
        i -= 1
    return lst
  

insert(3,[1,2,4,5])
[1, 2, 3, 4, 5]
Daniel Hao
  • 4,922
  • 3
  • 10
  • 23
0

Easy, we can even do it by replacing only one of the ...:

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

Testing it:

>>> insert(3,[1,2,4,5])
[1, 2, 3, 4, 5]
superb rain
  • 5,300
  • 2
  • 11
  • 25
-2

Taking inspiration from the answer above, I would say something that also duplicates the list instead of overwriting on it, like the following

def insert_and_sort(a, tab):
    newtab = list(tab)
    newtab.append(a)
    sort(newtab)
    return newtab