【问题标题】:Google foobar question 1, minion job handlingGoogle foobar 问题一,minion 作业处理
【发布时间】:2021-07-07 20:37:17
【问题描述】:

我最近收到了 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

提前致谢。

【问题讨论】:

  • 这段代码会立即出错,因为它没有正确缩进。

标签: python python-2.7 function dictionary oop


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-14
    • 1970-01-01
    • 2020-09-11
    • 2015-02-13
    • 2014-09-12
    相关资源
    最近更新 更多