Back-To-School Deals - hours only!Up to 80% off on all courses and bundles.-Close
Recap
Iterating over a list
Modifying lists
Working with multiple lists
15. Intersection of two sorted lists
Congratulations

Instruction

Great! The last type of programming problem we want to introduce is finding common elements in two sorted lists. Suppose we have the following sorted lists:

mark_sleep_durations = [268, 290, 323, 326, 345, 394, 434, 506, 590, 590]
kate_sleep_durations = [268, 299, 323, 440, 474, 546, 562, 590]

Do Mark and Kate share any identical sleep duration values?

This problem is actually quite similar to the one you just solved, merging two sorted lists. That's why we'll leave it for you to figure out in the exercise.

Exercise

Create a new sorted list named common_sleep_durations containing elements common to both lists from the template code. Use two temporary variables, i and j. Try to find a solution similar to the one used for merging two sorted lists. At the end of your code, print the common_sleep_durations list.

Stuck? Here's a hint!

Use the same while loop as in the previous exercise:

while i < len(mark_sleep_durations) and j < len(kate_sleep_durations):

Inside, apply the following rules:

  1. If mark_sleep_durations[i] is less than kate_sleep_durations[j], increment i.
  2. If mark_sleep_durations[i] is greater than kate_sleep_durations[j], increment j.
  3. If they are equal, add either element to common_sleep_durations.