Interleaving lists

Viewed 58
#No use of sort or sorted is allowed to me
def interleaved(lst1,lst2):
   sorted_Lst=[]
   i=0
   j=0
   while i in range(len(lst1)-1) and j in range(len(lst2)-1):
        if lst1[i]<lst2[j]:
            sortedLst.append(lst1[i])
            i+=1
        else:
            sortedLst.append(lst2[j])
            j+=1

  return sorted_Lst

I used a while loop here but I think we need to run it till the items run out and nothing is left to compare but I am not able to figure it out. we must interleave by iterating over the two sequences simultaneously, choosing the the smallest current number from each sequence.

Sample usage:

>>> interleaved( [-7, -2, -1], [-4, 0, 4, 8])
[-7, -4, -2, -1, 0, 4, 8]

>>> interleaved( [-4, 0, 4, 8], [-7, -2, -1])
[-7, -4, -2, -1, 0, 4, 8]

>>> interleaved( [-8, 4, 4, 5, 6, 6, 6, 9, 9], [-6, -2, 3, 4, 4, 5, 6, 7,8])

[-8, -6, -2, 3, 4, 4, 4, 4, 5, 5, 6, 6, 6, 6, 7, 8, 9, 9]
1 Answers

The case where either list ends and the other one has items left isn't covered. The logic should ideally be

def interleaved(lst1,lst2):
    sortedLst=[]
    i=0
    j=0
    while i < len(lst1) and j < len(lst2):
        if lst1[i]<lst2[j]:
            sortedLst.append(lst1[i])
            i+=1
        else:
            sortedLst.append(lst2[j])
            j+=1
    sortedLst += lst1[i:] # if first list has remaining items
    sortedLst += lst2[j:] # if second list has remaining items
    
  return sortedLst
Related