I am trying to implement a function that merges two ordered lists into a third (ordered) one, but duplicates have to be discarded (basically the last step of a mergesort).
I think that this code can be generalized to an arbitrary number or lists, by keeping a list of indices, rather than 2 explicit ones.
def merge_no_duplicates(list_1, list_2):
i = j = 0
import collections
result = collections.deque()
while i < len(list_1) and j < len(list_2):
if len(result) > 1 and list_1[i] == result[-1]:
i += 1
continue
if len(result) > 1 and list_2[j] == result[-1]:
j += 1
continue
if list_1[i] <= list_2[j]:
result.append(list_1[i])
i += 1
elif list_2[j] < list_1[i]:
result.append(list_2[j])
j += 1
# we still need to consume part of list_2
if i == len(list_1):
while j < len(list_2):
if list_2[j] == result[-1]:
j += 1
continue
result.append(list_2[j])
j += 1
# still need to consume part of list_1
if j == len(list_2):
while i < len(list_1):
if list_1[i] == result[-1]:
i += 1
continue
result.append(list_1[i])
i += 1
return result
Possible improvements: factor out the repetitive parts, for example by using something similar to this helper function:
check_duplicates(my_list, index):
if my_list[index] == result[-1]:
index += 1
Unfortunately this won't work (index
is a parameter, and will not influence the behavior of i
or j
). Is this possible at all?