Skip to content
Advertisement

I am merging to list with ascending order

If either i or j reach the end of their list range, how i copy the remainder of the other list to the merge list https://ibb.co/m9JzBYp go to link if not get the question

 def list_merge (x, y):
    merge = []
    i = 0
    j = 0
    total = len (x) + len(y)
    while != total :
       if x[i] < y[j]:
       merge.append(x[i])
       i += 1
       if i >= len (x):
      #how i copy the reminder
    else :
      merge.append(y[j])
      j += 1
      if j >= len (y):
     #how i copy the reminder
    return merge

Advertisement

Answer

EDIT – OP wanted the code in some specific way.. Please see second snippet.

Don’t try to complicate your code.. just go with how you would do it manually and write the code.

def list_merge (x, y):
    merged_list = []
    i = 0
    j = 0
    
    # when one of them is empty, break out
    while i < len(x) and j < len(y):
      if x[i] <= y[j]:
        merged_list.append(x[i])
        i +=1
      else:
        merged_list.append(y[j])
        j +=1
    
    # if you are here, that means either one of the list is done
    # so check the bounds of both lists and append the one which is not traversed

    # x has some elements to add
    # check how extend works... makes your code clean
    if i != len(x):
      merged_list.extend(x[i:])
    else:
      merged_list.extend(y[j:])

    return merged_list

a = [1,3,5,7,10]
b = [2,4,6,8,100]
print(list_merge(a,b))

Output

[1, 2, 3, 4, 5, 6, 7, 8, 10, 100]

What OP needed

def list_merge (x, y):
  merge = []
  i = 0
  j = 0
  total = len (x) + len(y)
  while len(merge) != total :
    if x[i] < y[j]:
      merge.append(x[i])
      i += 1
      if i >= len (x):
        merge.extend(y[j:])
    else:
      merge.append(y[j])
      j += 1
      if j >= len (y):
        merge.extend(x[i:])

  return merge

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement