问题描述
我正在用 Python 编写一个均值模式计算器,但遇到了这个错误。
此代码中的 new_arr
函数中的 mode
列表没有返回正确的最小值
我该如何纠正?
代码:-
import collections
import statistics
from statistics import StatisticsError
elemag = int(input())
raw_arr = input()
arr = raw_arr.split(" ")
def mean(total,split_arr) :
sum = 0
for i in split_arr :
sum += int(i)
return (sum/total)
def median (total,split_arr) :
new_arr = []
for i in split_arr :
new_arr.append(int(i))
new_arr.sort()
if total % 2 != 0 :
mid_val_index = int(((total + 1)/2) - 1)
return (new_arr[mid_val_index ])
else:
a = int(total/2)
b = int(a - 1)
c = int(new_arr[a])
d = int(new_arr[b])
return (c+d)/2
def mode(split_arr) :
new_arr = []
for i in split_arr :
new_arr.append(int(i))
try :
return statistics.mode(new_arr)
except StatisticsError as err :
return min(new_arr)
print(mean(elemag,arr))
print(median(elemag,arr))
print(mode(arr))
解决方法
听起来您使用的是 Python 3.8。 documentation 说:
在 3.8 版中更改:现在通过返回遇到的第一个模式来处理多模式数据集。以前,当找到多个模式时,它会引发 StatisticsError
。