We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
n = int(input())
raw = input().split()
x = [int(i) for i in raw]
def mean(arr):
return sum(arr)/len(arr)
def median(arr):
sorted_arr = sorted(arr)
a = (len(arr)-1)//2
b = a + 1
return (sorted_arr[a]+sorted_arr[b])/2
def mode(arr):
sorted_arr = sorted(arr)
sorted_set = list( set(sorted_arr))
occurances = {item : sorted_arr.count(item) for item in sorted_set}
#in case there are multiple occurances of multiple items
n_dept_occ = []
for key, value in occurances.items():
if max(occurances.values()) == 1:
return min(occurances.keys())
elif value == max(occurances.values()):
n_dept_occ.append(key)
return min(n_dept_occ)
print(mean(x))
print(median(x))
print(mode(x))
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Day 0: Mean, Median, and Mode
You are viewing a single comment's thread. Return to all comments →
n = int(input()) raw = input().split() x = [int(i) for i in raw]
def mean(arr): return sum(arr)/len(arr)
def median(arr): sorted_arr = sorted(arr) a = (len(arr)-1)//2 b = a + 1 return (sorted_arr[a]+sorted_arr[b])/2
def mode(arr): sorted_arr = sorted(arr) sorted_set = list( set(sorted_arr)) occurances = {item : sorted_arr.count(item) for item in sorted_set} #in case there are multiple occurances of multiple items n_dept_occ = [] for key, value in occurances.items(): if max(occurances.values()) == 1: return min(occurances.keys()) elif value == max(occurances.values()): n_dept_occ.append(key) return min(n_dept_occ)
print(mean(x)) print(median(x)) print(mode(x))