【发布时间】:2018-08-20 08:44:26
【问题描述】:
我有一长串整数,我想计算高于或高于平均值十分之一的数字的百分比。也就是我要计算分数mean / 10的百分位数。这是一种幼稚的方法(在 Python 中,但这并不重要):
ls = [35,35,73,23,40,60,5,7,3,4,1,1,1,1,1]
length = 0
summ = 0
for i in ls:
length += 1
summ += i
mean = float(summ) / float(length)
print('The input value list is: {}'.format(ls))
print('The mean is: {}'.format(mean))
tenth_mean = mean / 10
print('One tenth of the mean is: {}'.format(tenth_mean))
summ = 0
for i in ls:
if (i >= tenth_mean):
summ += 1
result = float(summ) / float(length)
print('The percentage of values equal or above one tenth of the mean is: {}'.format(result))
输出:
The input value list is: [35, 35, 73, 23, 40, 60, 5, 7, 3, 4, 1, 1, 1, 1, 1]
The mean is: 19.3333333333
One tenth of the mean is: 1.93333333333
The percentage of values equal or above one tenth of the mean is: 0.666666666667
这种方法的问题是我必须循环列表两次。有什么聪明的方法可以避免这种情况吗?
我看不到任何数据,因为我首先需要计算平均值才能知道要在计数中保留哪些值(第二个循环)。
此外,我想对多个百分比执行此操作(即平均值的十分之一、平均值的五分之一等)。这可以在第二个循环中轻松实现。我只是想指出这一点。
输入数组不服从任何分布。
编辑:可能值的范围只有几千个。值的总数约为 30 亿。
编辑:修正了上面“百分比”一词的用法。
【问题讨论】:
-
您负责创建列表吗?或者它是给定的输入?您可以在创建列表时计算列表的平均值并保存 1 个循环。不过,这不会改变您的时间复杂度。
-
"我想计算第 k 个百分位数,其中 k = mean / 10"。这不是“百分位”的意思。您的问题的其余部分表明您要计算分数的百分位数
mean/10。 -
@Prune:是的,谢谢。我修正了措辞。
标签: algorithm math percentile