Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can i have a nice explenation of what this lines of code are doing? -(data structures related )

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

Im 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 dont 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. :

lets say we have an example 2 lists:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading