Home > Software design >  How to calculate quartiles in Python without import
How to calculate quartiles in Python without import

Time:02-24

I have a school prodject were we need to calculate the quartiles of a list (list should be able to be both an even and an uneven list) in python. I am not allowed to use import (exept math.floor/math.ceil) to make things easier. I just can't get it to work though because I sometimes get a value thats plus or minus 0.5. (so if i wanted 3 for an example i get 2.5 or 3.5 depending on the combination and amount of numbers in the list) Any suggestions?

The code i have thus far looks like this:

def quartile_one(x):
    x.sort()
    k = 0
    if (len(x)%2) == 0:
        k = (math.floor((len(x)   1)*0.25))
        return ((x[k - 1])   (x[k]))/2
    else:
        k = (math.floor((len(x)   1)*0.25))
        return x[k - 1]

def quartile_three(x):
    x.sort()
    k = 0
    if (len(x)%2) == 0:
        k = (math.floor(len(x)*0.75))
        return (((x[k - 1])   (x[k]))/2)
    else:
        k = (math.floor(len(x)*0.75))
        return x[k - 1]

x = [1,2,3,4,5,6,7,8,9]

print(quartile_one(x))
print(quartile_three(x))

(expected output: 2.5 and 7.5)

Thanks!

Sorry for any bad grammar.

CodePudding user response:

The position of the 1st and 3rd quartiles do not depend on N/2, they depend on N/4. This should produce correct numbers. I include a diagram showing where the quartile points are:

import math

# 1 2 3 4 5 6 
#   ^  ^  ^
# 1 2 3 4 5 6 7 
#   ^   ^   ^
# 1 2 3 4 5 6 7 8 
#    ^   ^   ^
# 1 2 3 4 5 6 7 8 9
#    ^    ^    ^
def quartile_one(x):
    x.sort()
    k = len(x) // 4
    if len(x) % 4 <  2:
        return (x[k-1]   x[k])/2
    else:
        return x[k-1]

def quartile_three(x):
    x.sort()
    k = 3 * len(x) // 4
    if len(x) % 4 <  2:
        return (x[k]   x[k 1])/2
    else:
        return x[k]

x = [1,2,3,4,5]
for z in (6,7,8,9):
    x.append(z)
    print(x)
    print(quartile_one(x))
    print(quartile_three(x))
  • Related