python - 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
提前致谢。
解决方案
您可以使用collections.Counter
列表推导过滤掉任何出现n
或多次出现的元素
from collections import Counter
def solution(data, n):
c = Counter(data)
return [i for i in data if c[i] < n]
推荐阅读
- c# - 我没有从数据库中获取任何数据
- javascript - 刺激点击按钮。问题
- javascript - 基于行和列将 JSON 导出为 CSV
- javascript - 标识符‘setValues’已经被声明”
- javascript - 如何在向 Spring API 发送查询方向的 javascript 中格式化 Pageable json 对象
- python - 使用 Python 从字母数字文本中分离文本和数字
- filesystems - 是否在所有文件系统上按顺序写入没有搜索的文件?
- r - 根据另一个矩阵中相应单元格中的值将值更改为一个矩阵
- css - 如何使用剪辑路径制作圆角三角形
- sql - 将 Oracle SQL 转换为 SQL Server