如果需要,实现了一个简单的分位数函数,该函数使用线性插值来获取两个索引之间的值。
def calc_quantile(lst, q):
s_lst = sorted(lst)
idx = (len(s_lst) - 1)*q
int_idx = int(idx)
remainder = idx % 1
if remainder > 0:
lower_val = s_lst[int_idx]
upper_val = s_lst[int_idx + 1]
return lower_val * (1 - remainder) + upper_val * remainder
else:
return s_lst[int_idx]
使用以下扩展代码编辑了我的回复,以匹配您的测试用例:
def calc_quantile(lst, q, method='linear'):
if not lst:
return ValueError("list is empty, cannot calculate quantile")
if not 0 <= q <= 1:
return ValueError("q must be in the domain 0 to 1")
if method not in ['linear', 'left-side', 'average']:
return NotImplementedError("the chosen method has not been implemented")
s_lst = sorted(lst)
idx = (len(s_lst) - 1)*q
int_idx = int(idx)
remainder = idx % 1
if remainder > 0 and method != 'left-side':
lower_val = s_lst[int_idx]
upper_val = s_lst[int_idx + 1]
if method == 'linear':
return lower_val * (1 - remainder) + upper_val * remainder
else:
return (lower_val + upper_val) / 2
else:
return s_lst[int_idx]
print(calc_quantile([1, 3, 4, 6, 4, 2], 0.25, 'left-side')) # 2
print(calc_quantile([1, 3, 5, 6, 1, 4, 2], 0.25, 'left-side')) # 1
print(calc_quantile([1, 3, 3, 5, 6, 2, 4, 1], 0.25, 'average')) # 1.5