How do you find the median of a list without inbuilt in python?

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    Sometimes, while working with Python list we can have a problem in which we need to find Median of list. This problem is quite common in the mathematical domains and generic calculations. Let’s discuss certain ways in which this task can be performed.

    Method #1 : Using loop + "~" operator
    This task can be performed in brute force manner using the combination of above functionalities. In this, we sort the list and the by using the property of “~” operator to perform negation, we access the list from front and rear, performing the required computation required for finding median.

    test_list = [4, 5, 8, 9, 10, 17]

    print["The original list : " + str[test_list]]

    test_list.sort[]

    mid = len[test_list] // 2

    res = [test_list[mid] + test_list[~mid]] / 2

    print["Median of list is : " + str[res]]

    Output :

     
    The original list : [4, 5, 8, 9, 10, 17]
    Median of list is : 8.5
    

    Method #2 : Using statistics.median[]
    This is the most generic method to perform this task. In this we directly use inbuilt function to perform the median of the list.

    import statistics

    test_list = [4, 5, 8, 9, 10, 17]

    print["The original list : " + str[test_list]]

    res = statistics.median[test_list]

    print["Median of list is : " + str[res]]

    Output :

     
    The original list : [4, 5, 8, 9, 10, 17]
    Median of list is : 8.5
    


    Mean, Median, Mode are the three most common types of averaging used in mathematics. With the Mean being what people most conventionally associate with the word “average”.

    Mean:

    The Mean of a list of numbers is what people most commonly refer to when talking about the “average” of a set of numbers. It is found by taking the sum of all the numbers and dividing it by the number of numbers [length of the list]. In the example below we will write a function called “mean” and it will use Python’s built in sum[] function to add up all numbers in our list and Pythons built in len[] function to get the length of our list[the number of numbers].

    We can now test our function out use a random list like [1,2,3,4,5], since [1+2+3+4+5]=15 and since we have 5 numbers we divide by 5: 15/5=3 so our expected output will be 3.

    This function will work for any length of input

    Median:

    The Median of a list of numbers will be the middle number. If there is an even number of elements in the list then we will take the mean of the middle two numbers [add them up and divide by 2].

    We will start off by sorting the list and checking if the list length is odd. We will do this by checking if the length of the list modulus 2 is one: len[lst]%2=1 [if you do not know what modulus is, its taking a number on the left of the percent sign, [list length in this case] and dividing it by the number on the right [2 in this case] as many times as possible and seeing what the remainder would be]. If the length is odd then we want to return the middle number which will be the length divided by 2 rounded down to the nearest integer: len[lst]//2 [the two slashes represent floor division which means that we want to round down to the nearest whole number]

    The function we have written so far will work as long as lst has an odd number of elements. We now want to add an else statement which will run if the list length is even and it will return the sum of the two middle numbers divided by two . The two middle numbers will be indexed at the length of the array divided by two minus one and the length of the array dividied by two . This is because lists in python start with an index of zero, the first element of our list can be accessed with lst[0].

    Note: We still use floor division in the else statement even though we will always be left with whole numbers because regular division returns a float type number such as 1.0 , 2.0, 3.0 but we need integer type numbers[whole numbers] to use as indexes for our array so I like to use floor division, alternatively you could write int[len[lst]] but that looks more complicated in my opinion.

    We can now test it out, be sure to test both even and odd amounts of numbers to ensure the function is working correctly:

    Since 3 is the middle number we know it’s working ok

    Since we have an even amount of numbers we want to add the middle two together[3,4] and divide them by two [3+4]/2=3.5 since that is the same as what our function is showing us we know it is working correctly.

    Mode:

    The Mode of a list are the numbers in the list which occur most frequently. We will calculate it by finding the frequency of each number present in the list and then choose the one’s with the highest frequency.

    We want to start off by creating a dictionary we will call it “frequency” that will store the number and its frequency, data will be of the form frequency[number]=# of occurrences. We will then loop through our list and input all the numbers into our frequency dictionary.

    Note: if you do not know what set defualt does, all it does is it checks if the number is in our dictionary, if it is not in our dictionary then it will add it in our dictionary and set it equal to zero. I have added a print statement so I can show you a visual representation of what the code is doing so far.

    we now want to find the highest value in our dictionary which can be done by by converting all our values into a list by using pythons built in .values[] function on our dictionary to create a list. we can then use Pythons built in max[] function to find the highest value in that list.

    Note: that the print statement was added to show what is happening and that the variable names are made up by me and can be anything.

    If we plug in our same data set as before:

    We can see that the highest frequency number[s] occur twice in our list. We now want to create a new list, by looping through our dictionary and adding any key with a value of highestFrequency[in this case 2] to it. We then want to return that list.

    Note: .items[] is a built in python function that turns a dictionary into a list of tuples that represent key value pairs.

    We can now try the example from before:

    We can also try an example where evey number occurs exactly once

    Since every number in our list has the same frequency every number will be the mode.

    How do you find the median without an inbuilt function in Python?

    Program to find Mean, Median, and Mode without using Libraries:.
    Mean: numb = [2, 3, 5, 7, 8] no = len[numb] summ = sum[numb] mean = summ / no print["The mean or average of all these numbers [", numb, "] is", str[mean]] ... .
    Median: ... .
    Mode: ... .
    Program to find Mean, Median, and Mode using pre-defined library:.

    How do you find the median in Python manually?

    Tip: The mathematical formula for Median is: Median = {[n + 1] / 2}th value, where n is the number of values in a set of data. In order to calculate the median, the data must first be sorted in ascending order. The median is the number in the middle.

    How do you find the median of a list in Python?

    You can write your own function in Python to compute the median of a list..
    def get_median[ls]:.
    # sort the list..
    ls_sorted = ls. sort[].
    # find the median..
    if len[ls] % 2 != 0:.
    # total number of values are odd..
    # subtract 1 since indexing starts at 0..
    m = int[[len[ls]+1]/2 - 1].

    How do you find the median of a list?

    To find the median value in a list with an even amount of numbers, one must determine the middle pair, add them, and divide by two.

    Chủ Đề