Skip to content

Instantly share code, notes, and snippets.

@iximiuz
Last active August 15, 2018 09:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iximiuz/d9b4a87c2c948ed7bc91 to your computer and use it in GitHub Desktop.
Save iximiuz/d9b4a87c2c948ed7bc91 to your computer and use it in GitHub Desktop.
Mean, median, mode and stddev calculation in Python 3
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]
@rickyngan
Copy link

call 'sample.sort()' before evaluating 'median = (sample[n//2 - (n + 1)%2] + sample[n//2])/2'

@rickyngan
Copy link

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