Reputation:
So I want to find the 1st quartile and 3rd quartile for a list like [1,2,3,4,5,6,7,8,9,10]
but I can't use any modules outside other than math
, and nope, I can't use numpy
, as this is program is for my calculator's micro-python, which doesn't allow importing of external modules, so I'm trying to find a way to do it with pure python only, i've already found a way to get the median, and the 1st quartile, but improvements are welcome.
# lower quartile
if number_of_data % 2 == 0:
median1 = sorted_listed_data[number_of_data//4]
median2 = sorted_listed_data[number_of_data//4 - 1]
median = round((median1 + median2)/2, 5)
else:
median = round(sorted_listed_data[number_of_data//4], 5)
# median
if number_of_data % 2 == 0:
median1 = sorted_listed_data[number_of_data//2]
median2 = sorted_listed_data[number_of_data//2 - 1]
median = round((median1 + median2)/2, 5)
else:
median = round(sorted_listed_data[number_of_data//2], 5)
Upvotes: 0
Views: 4464
Reputation: 57
def quartile(my_list): #Avoid using recursive function to save memory
length = len(my_list) #using copies of long data list
start = (length)//2
if length%2:
start = start
end = start + 1
median = sum(my_list[start:end]) # sum single element list as value
else:
start = start - 1
end = start + 2
median = sum(my_list[start:end]) / 2. # Average middle two elements
#Compute Quatrile 1
q1start = start//2
flag = False
if start%2:
q1start = q1start
q1end = q1start + 1
q1 = sum(my_list[q1start:q1end]) # a single element
else:
flag = True
q1start = q1start - 1
q1end = q1start + 2
q1 = sum(my_list[q1start:q1end]) / 2. # Average middle two elements
#Compute Quartile 3
q3start = end + q1start
q3end = end + q1end
if flag:
q3 = sum(my_list[q3start:q3end]) / 2.
else:
q3 = sum(my_list[q3start:q3end])
return q1, median, q3
odd_list = [1,2,3,4,5,6,7, 8, 9,10,11,12,13,14,15]
odd_list2 = [1,3,6,9,12,15,17.5,18, 20.4, 25,28,31,35,38,41,44,48]
even_list = [1,2,3,4,5,6, 7,8, 9,10,11,12,13,14]
even_list2 = [1,2,4.4,6, 8.5, 10,11,12,14, 16,17,18,18.5,19,20,21,22,25,28,30]
neg_list = [-12,-11.5,-10,-8,-7.5, -6,-5.5, -4,-1.2,-1,-0.5,-0.4]
print(quartile(odd_list))
print(quartile(odd_list2))
print(quartile(even_list))
print(quartile(even_list2))
print(quartile(neg_list))
Upvotes: 0
Reputation:
These allow finding the 1st quartile, median, and 3rd quartile in python for a list like [1,2,3,4,5,6,7,8,9,10]
, if the list is unsorted then sort it using list.sort()
def find_median(List): # finds the median of a sorted_list
number_of_data = len(List)
if number_of_data % 2 == 0:
median = (List[(number_of_data//2)]+List[(number_of_data//2-1)])/2
else:
median = List[(number_of_data//2)]
return median
middle = len(sorted_listed_data)//2
# lower quartile
lower_quartile = find_median(sorted_listed_data[:middle])
# median
median = find_median(sorted_listed_data)
# upper quartile
upper_quartile = find_median(sorted_listed_data[middle:])
Upvotes: 1