Created
March 11, 2020 15:04
-
-
Save les-peters/2cd90052d82446ea12e5c3109aa0c9e6 to your computer and use it in GitHub Desktop.
Cassidoo IQofW 2020-03-09
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This week's question: | |
# Given an array of unsorted integers, return the mean, median, and mode. | |
import math | |
from functools import reduce | |
def mean_median_mode(N): | |
print('given', N) | |
SN = sorted(N) | |
mean = 0 | |
median = 0 | |
mode = [] | |
l = len(N) | |
if l == 2: | |
mean = (N[0] + N[1]) / 2 | |
median = mean | |
mode.append(N[0]) | |
mode.append(N[1]) | |
else: | |
mean = reduce((lambda x, y: x + y), SN) / l | |
mid = math.floor(l/2) | |
if (l % 2) == 1: | |
median = SN[mid] | |
else: | |
median = (SN[mid] + SN[mid - 1]) / 2 | |
if int(median) == math.floor(median): | |
median = int(median) | |
mode_count = [0] * (1 + SN[-1]) | |
# accumulate counts of each member of the set | |
for i in range(l): | |
mode_count[SN[i]] += 1 | |
# determine value of greatest occurance | |
max = 0 | |
lSN = len(SN) - 1 | |
for i in range(lSN): | |
if mode_count[i] > max: | |
max = i | |
# determine which set values have highest occurance | |
for i in range(len(mode_count)): | |
if mode_count[i] == mode_count[max]: | |
mode.append(i) | |
return { 'mean': mean, 'median': median, 'mode': mode } | |
N = [ 1, 2 ] | |
print(mean_median_mode(N)) | |
N = [ 5, 2, 1, 4, 3 ] | |
print(mean_median_mode(N)) | |
N = [ 5, 2, 1, 4, 4, 3 ] | |
print(mean_median_mode(N)) | |
N = [ 5, 2, 1, 4, 4, 3, 6, 6 ] | |
print(mean_median_mode(N)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment