From 752006c58233fdb0ddd387a34ec6c119bb788034 Mon Sep 17 00:00:00 2001 From: Shriprajwal Date: Thu, 3 Oct 2019 14:32:17 +0530 Subject: [PATCH] Added the median snippet --- snippets/median.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 snippets/median.md diff --git a/snippets/median.md b/snippets/median.md new file mode 100644 index 000000000..aa63231bb --- /dev/null +++ b/snippets/median.md @@ -0,0 +1,23 @@ +--- +title: median +tags: math,median,beginner +--- +Find the median of a list of numbers + +Sort the numbers of the list using the sort function and find the median, which is the middlemost element of the list. + +```py +def median(list): + list.sort() # The sort function of python + list_length = len(list) + if list_length%2==0: + return (list[int(list_length/2)-1] + list[int(list_length/2)])/2 # Mean of the middle two elements + else: + return list[int(list_length/2)] # The element in the middle + +``` + +```py +median([1,2,3]) # 2 +median([1,2,3,4]) # 2.5 +```