Skip to content
Advertisement

The function must insert the values ​from the second list, one by one, into the first list so that it stays sorted at each step

I’m new to python and I need to do the code described in the title without using sort() or append() but I’ve been stuck for hours and I can’t progress more…

def insereOrdenado(lista1,lista2):

  for i in range(len(lista2)):
    for j in range(len(lista1)): 
      if lista2[i] < lista1[j]:
        lista1.insert(j, lista2[i])      

  return lista1

insereOrdenado([1, 2, 4, 5], [-1, 3, 5, 6])

The first number in list 2 keeps repeating itself and I don’t know how to make it stop, and I haven’t figured out how to add the values ​​in list 2 that are greater than those in list 1. Please helpp :(

Advertisement

Answer

def insereOrdenado(lista1,lista2):

  for i in range(len(lista2)):
    for j in range(len(lista1)): 
      if lista2[i] < lista1[j]:
        lista1.insert(j, lista2[i])   
        break
      elif lista2[i] > max(lista1):
        lista1.insert(len(lista1),lista2[i])
      elif lista2[i] in lista1:
        break
        

  return lista1

print(insereOrdenado([1, 2, 3], [-1, 2, 6,7]))

You have to use break statement in the second loop so if you insert some value to lista1 it will terminate the second loop and will continue from the first loop. Second elif statement will take care of bigger values in lista2 and third elif statement will test if any value in lista2 is already in lista1 will break the second loop so there won’t be any recurrence in lista1

Advertisement