The middle element in the sequence of the duplicated elements can be retained only. For example, the list like [1, 2, 1, 3, 1] is processed and its output should be [2, 1, 3] because there are three ‘1’ in the list, and the red one can be retained as it’s the middle one, and the first and third ones are removed. If the number of the duplicated elements is even, the right one over the middle is retained. For example, the output of [ 1, 2, 1, 3, 1, 1] is [2, 3, 1] because there are four ones, and the third (orred) one is the one just over the middle. There are more examples as follows to help you to understand the rule. The red elements in the lists are the elements which should be retained.
[2, 1, 2, 3, 1] -> [2, 3, 1]
[3, 2, 1] -> [3, 2, 1]
[1, 2, 3, 3, 2, 1] -> [3, 2, 1]
[3, 2, 1, 1, 2, 3, 2, 1, 3, 2] -> [1, 3, 2]
I was trying to implement this but I got the following output. Here is my implementation.
def remove_duplicates(numbers):
# Step 1: Initialize dictionary to track count and index
count_dict = {}
# Step 2: Count occurrences and store index
for index, num in enumerate(numbers):
if num in count_dict:
count_dict[num].append(index)
else:
count_dict[num] = [index]
# Step 3: Initialize list for final unique elements
unique_elements = []
# Step 4: Determine unique elements based on the rule
for num, indices in count_dict.items():
count = len(indices)
if count == 1:
unique_elements.append(num)
else:
middle_index = indices[count // 2 + count % 2 - 1]
unique_elements.append(numbers[middle_index])
# Step 5: Return the list of unique elements
return unique_elements
Output:
# expected
[1, 3, 2]
# got
[3, 2, 1]
Group indexes by value using collections.defaultdict
. Pull the middle index of each group. Sort the resulting indexes and use them to retrieve the corresponding values from the original list.
from collections import defaultdict
def remove_duplicates(arr):
d = defaultdict(list)
for i, k in enumerate(arr):
d[k].append(i)
return [arr[i] for i in sorted(v[len(v) // 2] for v in d.values())]