Home > Software design >  What are these data-structure-related lines of code doing?
What are these data-structure-related lines of code doing?

Time:05-02

I am in the middle of training a knowledge I got and redoing some exercise to keep the information good in my head.

I'm in an exercise of creating a function, that its target is iterating over 2 lists in the same time, and getting data from them into one list, that i need to return as the target output. Now, i already finished the exercise, just cant understand 2 lines at the end that got to be in there in order for me to pass the exercise. I am doing everything else fine only don't understand the necessity of those 2 lines of code. Would appreciate help in understanding the meaning of those in our words, and what they simply do, and why are they there simply.

Let's say we have an example 2 lists:

list1 = [1, 3, 5, 7, 9]
list2 = [1, 2, 3, 6, 8, 9, 10]

def get_sorted_union(list1, list2):
  i, j = 0, 0
  list_to_return = []
  while i < len(list1) and j < len(list2):
    if list1[i] > list2[j]:
      list_to_return.append(list2[j])
      j  = 1
    elif list1[i] < list2[j]:
      list_to_return.append(list1[i])
      i  = 1
    else:
      list_to_return.append(list1[i])
      i  = 1
      j  = 1
  list_to_return  = list1[i:] #Those are the 2 lines i cant understand why they exist. v
  list_to_return  = list2[j:]
  return list_to_return

CodePudding user response:

The last two lines are adding the remainder of the input lists to the output.

This is important when your input lists are of different length. For e.g.

list1 = [1,4,5]
list2 = [2]

Now, when the code reaches those lines, i = 1 and j = 1. Your list_to_return only has [1,2], but you want to add the remaining elements from list1 [4,5] to this list as well

CodePudding user response:

Once you get through the all the elements of one of the lists, there is a good chance the other list will still contain elements, and because of your AND clause, your while loop will no longer continue. list_to_return = list1[i:] appends any left over elements in list1 to list_to_return. [i:] means all elements from index i to the end of the list.

  • Related