【问题标题】:Timeout Issue in Looping Through Hackerrank Example循环通过 Hackerrank 示例中的超时问题
【发布时间】:2021-05-10 03:46:13
【问题描述】:

谁能解释为什么我的黑客等级示例代码超时。我对基于处理时间的代码效率的整体概念不熟悉。该代码似乎适用于小型数据集,但是一旦我开始使用大型数据集测试用例,它就会超时。我提供了对该方法及其上下文目的的简要说明。但是,如果您发现我正在使用的函数可能会消耗大量运行时,那么如果您能提供任何提示,那就太好了。

完成下面的候鸟功能。 参数: arr:通过索引看到的鸟类种类的数组。 例如。 arr = [Type1 = 1, Type2 = 4, Type3 = 4, Type4 = 4, Type5 = 5, Type6 = 3] 返回目击模式的最低类型。在这种情况下,4 次目击是 模式。 Type2 是具有模式的最低类型。所以返回整数 2。


def migratoryBirds(arr):
    # list of counts of occurrences of birds types with the same 
    # number of sightings
    bird_count_mode = []
    for i in range(1, len(arr) + 1):
        occurr_count = arr.count(i)
        bird_count_mode.append(occurr_count)
        
    most_common_count = max(bird_count_mode)
    common_count_index = bird_count_mode.index(most_common_count) + 1
    # Find the first occurrence of that common_count_index in arr
    # lowest_type_bird = arr.index(common_count_index) + 1
    # Expect Input: [1,4,4,4,5,3]
    # Expect Output: [1 0 1 3 1 0], 3, 4
    return bird_count_mode, most_common_count, common_count_index

附:感谢您的编辑克里斯查理。我只是尝试同时编辑它

【问题讨论】:

  • 这是完全错误的:occurr_count = arr.count(i)i 是一个列表索引,但count() 用于计算列表元素。应该是arr.count(arr[i])
  • 即使你做得对,它也是一个 O(n^2) 算法。您可以使用字典计算 O(n) 中的元素。还有一个库函数 collections.Counter() 可以为您完成这项工作。
  • @Barmar 所以我认为 collections.Counter() 更有效?抱歉,我不熟悉 O(n^2) 与 O(n) 的概念,但我现在正在研究它。
  • arr.count(i) 的每次调用都是 O(n),你执行它们 n 次,使得算法 O(n^2)。
  • collections.Counter() 大概使用类似for i in list: counter[i]+=1

标签: python timeout


【解决方案1】:

使用collections.Counter() 创建一个字典,将物种映射到它们的数量。从中获取最大计数,然后获取具有该计数的所有物种。然后在列表中搜索其中一个物种的第一个元素。

import collections

def migratoryBirds(arr):
    species_counts = collections.Counter(arr)
    most_common_count = max(species_counts.values())
    most_common_species = {species for species, count in species_counts if count = most_common_count}

    for i, species in arr:
        if species in most_common_species:
            return i

【讨论】:

  • 问题本身的说明不清楚。但我很确定基于问题的答案,他们的意思是返回鸟类类型的模式,而不是返回最低的。不过,这不是重点。我真正想知道的是计数器库函数是否更有效。
  • 我希望计数器库为 O(n),因为这是使用字典实现它的自然方式。并且说明清楚地表明当有多个模式实例时返回最低值。
猜你喜欢
  • 2019-05-17
  • 2022-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多