pythonlistquartile

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


I need to make a function q1 that calculates the 1st quartile of a list called: lst. i am not allowed to use any imports! When i run my function the answer is not correct. What can i change?

def q1(lst):
    lst.sort()

    middle = len(lst)//2

    k1 = median([middle])
    return k1

This is my median function:

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

Solution

  • Implemented a simple quantile function that uses linear interpolation to get the value between two indices, if required.

    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]
    

    Edited my reply with below extended code, to match your test-cases:

    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