首页 > 解决方案 > 如何在python中使用2500数组的自定义均值、中值、众数函数?

问题描述

所以我试图解决Hackerrank 上的均值、中值和众数挑战。我定义了 3 个函数来计算长度在 10 到 2500 之间(含)的给定数组的平均值、中位数和众数。

我收到一个包含 2500 个整数的数组的错误,不知道为什么。我查看了 python 文档,发现没有提到列表的最大长度。我知道我可以使用统计模块,但我想我会努力尝试并且很固执。对我的代码的任何帮助和批评表示赞赏。如果需要,请诚实和残酷。谢谢

N = int(input())
var_list = [int(x) for x in input().split()]

def mean(sample_list):
    mean = sum(sample_list)/N
    print(mean)
    return

def median(sample_list):
    sorted_list = sorted(sample_list)
    if N%2 != 0:
        median = sorted_list[(N//2)]
    else:
        median = (sorted_list[N//2] + sorted_list[(N//2)-1])/2
    print(median)
    return

def mode(sample_list):
    sorted_list = sorted(sample_list)
    mode = min(sorted_list)
    max_count = sorted_list.count(mode)
    for i in sorted_list:
        if (i <= mode) and (sorted_list.count(i) >= max_count):
            mode = i
    print(mode)
    return

mean(var_list)
median(var_list)
mode(var_list)

    Compiler Message

    Wrong Answer

    Input (stdin)

        2500
        19325 74348 68955 98497 26622 32516 97390 64601 64410 10205 5173 25044 23966 60492 71098 13852 27371 40577 74997 42548 95799 26783 51505 25284 49987 99134 33865 25198 24497 19837 53534 44961 93979 76075 57999 93564 71865 90141 5736 54600 58914 72031 78758 30015 21729 57992 35083 33079 6932 96145 73623 55226 18447 15526 41033 46267 52486 64081 3705 51675 97470 64777 31060 90341 55108 77695 16588 64492 21642 56200 48312 5279 15252 20428 57224 38086 19494 57178 49084 37239 32317 68884 98127 79085 77820 2664 37698 84039 63449 63987 20771 3946 862 1311 77463 19216 57974 73012 78016 9412 90919 40744 24322 68755 59072 57407 4026 15452 82125 91125 99024 49150 90465 62477 30556 39943 44421 68568 31056 66870 63203 43521 78523 58464 38319 30682 77207 86684 44876 81896 58623 24624 14808 73395 92533 4398 8767 72743 1999 6507 49353 81676 71188 78019 88429 68320 59395 95307 95770 32034 57015 26439 2878 40394 33748 41552 64939 49762 71841 40393 38293 48853 81628 52111 49934 74061 98537 83075 83920 42792 96943 3357 83393{-truncated-}
        Download to view the full testcase

    Expected Output

        49921.5
        49253.5
        2184

标签: python-3.xstatisticsmode

解决方案


您的问题似乎是您实际上是在使用标准列表操作,而不是动态计算事物,同时遍历数据一次(平均而言)。sum(sample_list)几乎肯定会给你一些超过双重限制的东西,因为它变得非常大。

进一步阅读


推荐阅读