微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

循环通过 Hackerrank 示例中的超时问题

如何解决循环通过 Hackerrank 示例中的超时问题

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

完成下面的migratoryBirds功能。 参数: 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,5,3]
    # Expect Output: [1 0 1 3 1 0],3,4
    return bird_count_mode,most_common_count,common_count_index

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

解决方法

使用 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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。