如何在不导入的情况下计算列表的第一和第三四分位数?

How to calculate the 1st and 3th quartile of a list without import?

我需要创建一个函数 q1 来计算列表的第一个四分位数:lst。 我不允许使用任何进口商品! 当我 运行 我的功能答案不正确。我可以改变什么?

def q1(lst):
    lst.sort()

    middle = len(lst)//2

    k1 = median([middle])
    return k1

这是我的中值函数:

def median(lst):
    lst.sort()
    half_list = len(lst) // 2
    even = lst[half_list]
    odd = lst[-half_list-1]
    return (even + odd) / 2

中位数是排序列表的中间项,即len(lst)//2。 因此,列表的第一和第三四分位数是多少?

firstQIndex = len(lst)//4
thirdQIndex = (3*len(lst))//4
firstQ = lst[firstQIndex]
thirdQ = lst[thirdQIndex]

你可以试试这个功能(独立的,没有导入):

def quantile(x, y):
    n = int(round(y * len(x) + 0.5))
    return x[n-1]

并像这样打电话:

print(quantile(myList, 0.1))
print(quantile(myList, 0.3))

实现了一个简单的分位数函数,如果需要,该函数使用线性插值来获取两个索引之间的值。

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