Finding Mean, Median, Mode in Python without libraries


In this article, we will learn how to calculate Mean, Median and Mode with Python without using external libraries.

  1. Mean : The mean is the average of all numbers and is sometimes called the arithmetic mean. This code calculates Mean or Average of a list containing numbers:

      

    n_num = [1, 2, 3, 4, 5]

    n = len(n_num)

      

    get_sum = sum(n_num)

    mean = get_sum / n

      

    print("Mean / Average is: " + str(mean))

    Output:

    We define a list of numbers and calculate the length of the list. We then use sum() function to get sum of all the elements in a list. We finally divide the total sum by the number of elements in the list and we print the result to get the mean/average of a list.

  2. Median : The median is the middle number in a group of numbers. This code calculates Median of a list containing numbers:

      

    n_num = [1, 2, 3, 4, 5]

    n = len(n_num)

    n_num.sort()

      

    if n % 2 == 0:

        median1 = n_num[n//2]

        median2 = n_num[n//2 - 1]

        median = (median1 + median2)/2

    else:

        median = n_num[n//2]

    print("Median is: " + str(median))

    We define a list of numbers and calculate the length of the list. To find a median, we first sort the list in Ascending order using sort() function.
    Now we check if the number is even or odd by checking their remainders. If the number is even, we find 2 middle elements in a list and get their average to print it out. But if the number is odd, we find the middle element in a list and print it out.

  3. Mode : The mode is the number that occurs most often within a set of numbers. This code calculates Mode of a list containing numbers:

    from collections import Counter

      

    n_num = [1, 2, 3, 4, 5, 5]

    n = len(n_num)

      

    data = Counter(n_num)

    get_mode = dict(data)

    mode = [k for k, v in get_mode.items() if v == max(list(data.values()))]

      

    if len(mode) == n:

        get_mode = "No mode found"

    else:

        get_mode = "Mode is / are: " + ', '.join(map(str, mode))

          

    print(get_mode)

    We will import Counter from collections library which is a built-in module in Python 2 and 3. This module will help us count duplicate elements in a list.
    We define a list of numbers and calculate the length of the list. We then call Counter (a dict subclass) which helps to count hashable objects, and we then convert it to dict object. We then initialize a list with a For Loop to compare all the dict values (Number of elements) to the max of all dict values (count of most occurring element) and it returns all the elements equal to max count. If the elements returned are equal to the number of total elements in a list then we print out ‘No mode’, else we print out the modes returned.

Conclusion
We have successfully calculated mean, median and mode of a dataset but you might be thinking ‘Will I be using these algorithms every time I want to get mean, median and mode of a dataset?’
The answer is you can but you certainly won’t. This was just to show you how the algorithm works behind the scenes when finding out any of these.
For any projects, this can be achieved by simply importing an inbuilt library ‘statistics’ in Python 3 and using the inbuilt functions mean(), median() and mode(). Also, there are other external libraries which can help you achieve the same results in just 1 line of code as the code is pre-written in those libraries.



A self taught programmer and a core developer who has worked on various projects in HTML CSS Js Scratch Vbnet VBA C Python He has done Digital Marketing & ranked 2nd on Google in SERPs He has also created & contributed to some open source projects on Github


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the “Improve Article” button below.

Article Tags :



Be the First to upvote.

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.








Source link

TCS NQT 2018 (Recruitment Exam)


I am from “Institute of Engineering and Management, Kolkata”.

Round 1: TCS conducted a National Qualifier Test (NQT) as the first round of recruitment process this year. There was no concept of Campus Recruitment had happened this year. They fixed two specific dates for this NQT exam that was 2nd September 2018 and 3rd September 2018. There were 3 slots for each day. Question sets were the same for all for the same slot but different for either slot.

There were four sections in that online exam with sectional cut offs. four sections are 1. English test 2. Aptitude test 3. Computer proficiency test 4. Coding test.

My slot timing was in the 3rd slot on 2nd. English section was pretty much normal basically fill in the blanks type. In the aptitude section, there are two subsections one is normal and another is advanced. Computer proficiency section was also the same type and many questions were asked from ds and c-programming code snippet. And the last section was the Coding section.

Results were declared via mail on 8th September and I was luckily qualified in the first round. From our college, almost 650 students appeared for that exam and 413 students are qualified for the F2F interview.

 

Round 2: On the very next day of the first round result declaration I got another mail from TCS for the Interview date and place which was conducted on TCS Gitanjali Park office, Kolkata.

I had my interview on 11th September from 12 p.m and onwards. I arrived at the TCS office at 11.30 a.m. After waiting for a long I got my call around 4.15 p.m.

Now here I am going to share my interview experience. I will write interviewer 1 as I1, interviewer 2 as I2 and myself as M :

.

.

M: May I come in?

I1: Yes.

M: Good afternoon sir, good afternoon ma’am.

<< without giving any reply back >>

I1: Mainak, tell me the basic difference between the Ipv4 and Ipv6?

<<I have not mentioned “networking” in my resume >>

M: …. somehow manage to answer very basic.

I1: Seems not so happy. ” you are giving an answer, like a class 5 child”. Then again asked a question from networking.

I1: what is your final semester subsects?

M: After a big pause… Sorry, sir! I don’t know as currently, I am in 7th sem.

I1: So what is your 7th sem subjects and 6th sem subjects?

M: Ans with confidence.

<<As I was not prepared for this kind of questions. I lose my confidence took permission for having some water in between the interview process>>

I1: Final year project related questions

M: Ans with confidence.

I1: DBMS related questions

M: Answer

I1: Questions related to Extracurricular activities and some questions related to marketing.

M:  Manage to answer every question.

<In between this I2 was only observing me and my answers…. Not a single question was asked by her>

After the Interview, I was asked to wait outside. Again after waiting a long I was asked to leave for the day.

.

.

A few days later, results out and as expected my name was not there in the list.

From the 413 qualified students, only 192 students got the offer letter.

I can say Luck really matters a lot in case of every interview. If you get a good panel you will be hired easily.

Best Of Luck!!!!!!!!!!!!!

 

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the “Improve Article” button below.

Article Tags :



1

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.








Source link

Ways to write N as sum of two or more positive integers | Set-2


Given a number N, the task is to find the number of ways N can be partitioned, i.e. the number of ways that N can be expressed as a sum of positive integers.

Note: N should also be considered itself a way to express it as a sum of positive integers.
Examples:

Input: N = 5
Output: 7
5 can be partitioned in the following ways:
5
4 + 1
3 + 2
3 + 1 + 1
2 + 2 + 1
2 + 1 + 1 + 1
1 + 1 + 1 + 1 + 1

Input: N = 10
Output: 42

This post has been already discussed in Ways to write n as sum of two or more positive integers. In this post, an efficient approach is discussed.

Approach(Using Euler’s recurrence):
If p(n) is the number of partitions of N, then it can be generated by the following generating function:

sum_{n=0}^infty p(n)x^n = prod_{k=1}^infty left(frac {1}{1-x^k} right)

Using this formula and Euler’s pentagonal number theorem, we can derive the following recurrence relation for p(n): (Check the Wikipedia article for more details)

p(n) = p(n - 1) + p (n - 2) - p(n - 5) - p(n - 7) + cdots + (-1)^{|{k} - 1|} frac{k(3k - 1)}{2}

where k = 1, -1, 2, -2, 3, -3, … and p(n) = 0 for n < 0.

Below is the implementation of above approach:

#include <bits/stdc++.h>

using namespace std;

  

long long partitions(int n)

{

    vector<long long> p(n + 1, 0);

  

    

    p[0] = 1;

  

    for (int i = 1; i <= n; ++i) {

        int k = 1;

        while ((k * (3 * k - 1)) / 2 <= i) {

            p[i] += (k % 2 ? 1 : -1) * p[i - (k * (3 * k - 1)) / 2];

  

            if (k > 0)

                k *= -1;

            else

                k = 1 - k;

        }

    }

  

    return p[n];

}

  

int main()

{

    int N = 20;

    cout << partitions(N);

    return 0;

}

Time Complexity: O(N√N)
Space Complexity: O(N)



If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the “Improve Article” button below.

Article Tags :



Be the First to upvote.

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.


Source link