首页 > 解决方案 > 分配奴才做错了什么我的解决方案?

问题描述

编辑:我知道还有其他解决方案。我的问题是我做错了什么。我的逻辑在哪里简单。没有其他的。

正在用 Python 解决 minions 工作分配代码。问题如下

Write a function called solution(data, n) that takes in a list of less than 100 integers and a
number n, and returns that same list but with all of the numbers that occur more than n times
removed entirely. The returned list should retain the same ordering as the original list - you don't want to mix up those carefully planned shift rotations! For instance, if data was [5, 10,
15, 10, 7] and n was 1, solution(data, n) would return the list [5, 15, 7] because 10 occurs 
twice, and thus was removed from the list entirely.

我的代码如下

from collections import OrderedDict
def solution(data, n): 
    # Your code here
    if(len(data)>=100):
        return []
    seen=OrderedDict()
    s=[]
    for i in data:
        if i in seen:
            seen[i]+=1
        else:
            seen[i]=1
    for k in seen:
        if(seen[k]<=n):
            s.append(k)
    return s

我的逻辑是使用有序字典来跟踪数字和它们出现的次数。这样,我们可以在线性时间内完成代码,而不是 n^2(通过检查数据中每个值的计数)。这适用于大多数情况,但在某些情况下失败。我错过了什么?有空间限制吗?一些被忽视的案例?

标签: pythonpython-3.xlistdictionary

解决方案


推荐阅读