Last active
August 15, 2018 09:45
-
-
Save iximiuz/d9b4a87c2c948ed7bc91 to your computer and use it in GitHub Desktop.
Mean, median, mode and stddev calculation in Python 3
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
sample = [5, 3, 1, 2, 4] | |
n = len(sample) | |
mean = sum(sample)/n | |
median = (sample[n//2 - (n + 1)%2] + sample[n//2])/2 | |
stddev = (sum((e - mean)**2 for e in sample)/n)**0.5 | |
cnt = {} | |
for e in sample: | |
cnt[e] = cnt.get(e, 0) | |
cnt[e] += 1 | |
mode = sorted(cnt.keys(), key=lambda e: (cnt[e], -e))[-1] |
mode = max(set(sample), key= sample .count)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
call 'sample.sort()' before evaluating 'median = (sample[n//2 - (n + 1)%2] + sample[n//2])/2'