使用特殊规则删除重复元素

问题描述 投票:0回答:1

重复元素序列中的中间元素只能保留。例如, 像 [1, 2, 1, 3, 1] 这样的列表被处理并且它的输出应该是 [2, 1, 3] 因为有三个'1' 列表,红色的可以保留,因为它是中间的,第一和第三个是 删除。如果重复的元素个数为偶数,则保留中间右边的那个。 例如,[ 1, 2, 1, 3, 1, 1] 的输出是 [2, 3, 1] 因为有四个,第三个(orred)是刚好在中间的那个。 下面还有更多例子可以帮助您理解规则。列表中的红色元素 是应该保留的元素。

[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]

Photo of the question

我试图实现这个,但我得到了以下输出。这是我的实现。

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

输出:

# expected 
[1, 3, 2]

# got
[3, 2, 1]
python python-3.x list dictionary frequency
1个回答
1
投票

我只是创建一个元素计数器。然后遍历列表,减少计数器,如果计数 == 0,将项目添加到输出:

from collections import Counter

test_cases = [
    ([1, 2, 1, 3, 1, 1], [2, 3, 1]),
    ([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]),
]

def fn(l):
    c = Counter(l)
    out = []
    for v in l:
        c[v] -= 1
        if c[v] == 0:
            out.append(v)
    return out


for l, ans in test_cases:
    assert fn(l) == ans
© www.soinside.com 2019 - 2024. All rights reserved.