Merge pull request #130 from TheDaemonLord/master

[FEATURE]Added a snippet that finds the median
This commit is contained in:
Angelos Chalaris
2019-10-04 09:14:16 +03:00
committed by GitHub

23
snippets/median.md Normal file
View File

@ -0,0 +1,23 @@
---
title: median
tags: math,beginner
---
Finds the median of a list of numbers.
Sort the numbers of the list using `list.sort()` and find the median, which is either the middle element of the list if the list length is odd or the average of the two middle elements if the list length is even.
```py
def median(list):
list.sort()
list_length = len(list)
if list_length%2==0:
return (list[int(list_length/2)-1] + list[int(list_length/2)])/2
else:
return list[int(list_length/2)]
```
```py
median([1,2,3]) # 2
median([1,2,3,4]) # 2.5
```