'How to calculate quartiles in Python without import
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
