首页 > 解决方案 > Google foobar 问题一,minion 作业处理

问题描述

我最近收到了 google foobar 的邀请。我被困在第一个问题上。问题是:编写一个名为 solution(data, n) 的函数,该函数接受少于 100 个整数和一个数字 n 的列表,并返回相同的列表,但将所有出现超过 n 次的数字完全删除。返回的列表应保留与原始列表相同的顺序 - 您不想混淆那些精心计划的轮班轮换!例如,如果 data 是 [5, 10, 15, 10, 7] 并且 n 是 1,则 solution(data, n) 将返回列表 [5, 15, 7] 因为 10 出现了两次,因此从完整列出。它将在 Python 2.7.13 沙箱上运行

我自己编写了一些代码,并在 2.7 python 沙箱甚至我自己的 IDE 上对其进行了测试,它工作正常,但是当我验证它时,它只通过了两个测试(测试 1 和测试 3)而其他所有测试都失败了。请帮助我更正/改进代码。代码:

 from collections import Counter


    def solution(data, n):
        if len(data) < 100:  # Makes sure that it is only accepting integers below 100 i.e till 99
            counter = Counter(data)  # This counts how many of each element there are
            for element, count in dict(counter).items():  # Loop through the elements and their counts
                if count > n:  # If the count for the element is greater than n
                    for _ in range(count):  # Repeat as many times as the count
                        data.remove(element) # Remove the element from the original list
        print(data)
        return data
       else:
            break

提前致谢。

标签: pythonpython-2.7functiondictionaryoop

解决方案


您可以使用collections.Counter列表推导过滤掉任何出现n或多次出现的元素

from collections import Counter
def solution(data, n):
    c = Counter(data)
    return [i for i in data if c[i] < n]

推荐阅读