Very well done! Another typical problem is merging two sorted lists into a common sorted list. Suppose we have sleep duration times for two weeks in two separate, sorted lists:
sleep_durations_week_1 = [301, 346, 378, 410, 420]
sleep_durations_week_2 = [289, 317, 367, 414, 454]
We now want to create a common list containing all values from week 1 and week 2, sorted by amount. Take a look:
i, j = 0, 0
sorted_two_weeks = []
while i < len(sleep_durations_week_1) and j < len(sleep_durations_week_2):
if sleep_durations_week_1[i] < sleep_durations_week_2[j]:
sorted_two_weeks.append(sleep_durations_week_1[i])
i += 1
else:
sorted_two_weeks.append(sleep_durations_week_2[j])
j += 1
sorted_two_weeks += sleep_durations_week_1[i:]
sorted_two_weeks += sleep_durations_week_2[j:]
We use the temporary variables i
and j
. Here, i
represents the current index in sleep_durations_week_1
, and j
does the same for sleep_durations_week_2
.
We create a while
loop that continues until the end of either of the two lists. Inside the loop, we compare sleep_durations_week_1[i]
and sleep_durations_week_2[j]
. If sleep_durations_week_1[i]
is smaller, then we add this value to the list and increment i
by 1. Otherwise, we add sleep_durations_week_2[j]
to the list and increment j
by 1.
At some point, either i
or j
will point to the end of its respective list, but the other variable will still point to some remaining values in the other list. That's why we need to add those remaining elements after the while
loop terminates.