sim*_*ung 2 ruby ruby-on-rails
我已经编写了一种方法来计算一组数字的给定百分位数,以便在我正在构建的应用程序中使用.通常,用户需要知道给定数字集和第75百分位数的第25百分位数.
我的方法如下:
def calculate_percentile(array,percentile)
#get number of items in array
return nil if array.empty?
#sort the array
array.sort!
#get the array length
arr_length = array.length
#multiply items in the array by the required percentile (e.g. 0.75 for 75th percentile)
#round the result up to the next whole number
#then subtract one to get the array item we need to return
arr_item = ((array.length * percentile).ceil)-1
#return the matching number from the array
return array[arr_item]
end
Run Code Online (Sandbox Code Playgroud)
这看起来提供了我期待的结果,但任何人都可以重构这个或提供一个改进的方法来返回一组数字的特定百分位数?
mol*_*olf 12
一些评论:
Array不存在,[]则返回nil,因此Array不需要初始检查空.sort!的Array说法,因为你正在影响着项目的顺序Array 在调用你的方法的代码.使用sort(不!)代替.arr_length在分配后实际上并未使用.return最后一行语句是在Ruby中不必要的.也就是说,您编写的函数可以更简洁地编写,同时仍然可读.
def calculate_percentile(array, percentile)
array.sort[(percentile * array.length).ceil - 1]
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3279 次 |
| 最近记录: |