Python中的均值,中位数和众数

时间:2019-03-29 03:25:39

标签: python python-3.x

我正在用Hackerrank上的Python处理统计问题。当我输入值列表以计算模式时。它显示了运行时错误。

# Enter your code here. Read input from STDIN. Print output to STDOUT

N = int(input())
X = list(map(int, input().split()))
X.sort()

# Find the mean
mean = sum(X) / N
print(mean)

# Find the median
if N % 2 == 0:
    median = (X[N//2] + X[N//2 - 1]) / 2
else:
    median = X[N//2]

print(median)

# Find the mode
occurrence = list([1 for _ in range(N)])

for i in range(N):
    for j in range(i+1, N):
if X[i] == X[j]:
    occurrence += 1

if max(occurrence) == 1:
    mode = min(X)
else:
    mode = X[occurrence[max(occurrence)]]

print(mode)

当我为2500输入2500时,它只是向我显示了运行时错误。

这是测试用例的链接

enter link description here

3 个答案:

答案 0 :(得分:0)

我已经运行了您的代码,这是编译问题:

for i in range(N):
    for j in range(i+1, N):
if X[i] == X[j]:
    occurrence += 1

我认为您的意思是两个if中的for,例如:

    for i in range(N):
        for j in range(i + 1, N):
            if X[i] == X[j]:
                occurrence += 1

但是occurrence在这里列出,不能加1,我认为您的意思是计算int的出现并输出最大的1?您可以在此处使用defaultdictCounter,但是defaultdict仅在一个循环中。

    # import collections
    # import operator

    # Find the mode
    occurrence = collections.Counter(X)
    # occurrence = collections.defaultdict(int)
    #
    # for i in range(N):
    #     occurrence[X[i]] += 1

    mode = max(occurrence.items(), key=operator.itemgetter(1))[0]

    print(mode)

答案 1 :(得分:0)

您正在尝试为列表类型的出现添加1:

此外,我确定这可能是复制错误,但是您的循环不正确:

for i in range(N):
    for j in range(i+1, N):
if X[i] == X[j]:
    occurrence += 1

# It will be
for i in range(N):
    for j in range(i+1, N):
        if X[i] == X[j]:
            occurrence += 1

然后,您可能希望将发生的情况更改为:

occurrence[i] += 1

# from 
occurrence += 1

希望这会有所帮助

答案 2 :(得分:0)

这里是Mean,Median和Mode类。

import statistics
from collections import Counter

def median(list):
    n = len(list)
    s = sorted(list)
    return (sum(s[n//2-1:n//2+1])/2.0, s[n//2])[n % 2] if n else None

def mean(list):
    if len(list) == 0:
        return 0
    list.sort()
    total = 0
    for number in list:
        total += number
    return total / len(list)

def mode(list):
    counter = Counter(list)
    if len(counter) > 1:  
        possible_mode, next_highest = counter.most_common(2)
        if possible_mode[1] > next_highest[1]:
            return possible_mode[0]
    return "None"