• + 57 comments

    Python 3 - Dont reinvent the wheel ;)

    import numpy as np
    from scipy import stats
    
    size = int(input())
    numbers = list(map(int, input().split()))
    print(np.mean(numbers))
    print(np.median(numbers))
    print(int(stats.mode(numbers)[0]))
    
    • + 2 comments

      lol this is so elegant

      • + 1 comment

        here is problem solution in python java c++ and c programming language. https://programs.programmingoneonone.com/2021/05/hackerrank-day-0-mean-median-and-mode-solution.html

        • + 1 comment

          for my basic approach in c++ filter it by newest or jump to the solution https://www.hackerrank.com/challenges/s10-basic-statistics/forum/comments/861523

          • + 0 comments

            https://infosecgeek107746281.wordpress.com/2020/10/01/mean-median-mode-challenge-hackerrank/ or read from here

      • + 7 comments

        Here is my simple answer using java language

        import java.io.*;
        import java.util.*;
        
        public class Solution {
        
            public static double mean(int arr[], int n){
                long sum = 0;
                for(int i = 0; i < n; i++){
                    sum += arr[i];
                }
                double ans = (double) sum / (long) n;
                return ans;
            }
        
            public static double median(int arr[], int n){
                Arrays.sort(arr);
                int mid = n/2;
                double ans = ((double) arr[mid] + (double) arr[mid-1]) / 2;
                return ans;
            }
        
            public static int mode(int X[], int n){
                int mode=0,temp, count,max=0;
                for(int i=0;i<n;i++)
               {
                    temp=X[i];
                    count=0;
                    for(int j=0; j<n; j++)
                    {
                        if(temp==X[j])
                        {
                            count++;
                        }
                        if(count>max)
                        {
                            max=count;
                            if(max==1)
                            {
                                mode=X[0];
                            }
                            mode=temp;
                        }
                    }           
                }
                return mode;
            }
        
            public static void main(String[] args) {
                Scanner s = new Scanner(System.in);
                int n = s.nextInt();
                int arr[] = new int[n];
                for(int i = 0; i < n; i++){
                    arr[i] = s.nextInt();
                }
                System.out.format("%.1f\n", mean(arr, n));
                System.out.format("%.1f\n",median(arr, n));
                System.out.println(mode(arr, n));
                
            }
        }
        
        • + 0 comments

          Your median assumes an array with even number length.

        • + 0 comments

          how did you think the logic for the mode function??

        • + 1 comment

          import java.io.; import java.util.; import java.text.; import java.math.; import java.util.regex.*;

          public class Solution {

          public static void main(String[] args) {
              Scanner sc = new Scanner(System.in);
              int n = sc.nextInt();
              int []arr = new int[n];
              for(int i = 0; i<n; i++){
                  arr[i] = sc.nextInt();
              }
              System.out.format("%.1f\n", mean(arr, n));
              System.out.format("%.1f\n",median(arr, n));
              System.out.println(mode(arr, n));
          }
          
          public static double mean(int arr[], int n){
              long sum = 0;
              for(int i = 0; i<n; i++){
                  sum += arr[i];
              }
              double ans = (double) sum / (long)n;
              return ans; 
          }
          
          public static double median(int arr[], int n){
              Arrays.sort(arr);
              int mid = n/2;
              double ans;
              if(n%2 == 0){
                  ans = (((double)arr[mid] + (double)arr[mid-1])/2);
              } 
              else{
                  ans = (arr[mid]);
              }
              return ans;
          }
          
          public static int mode(int arr[], int n){
              Arrays.sort(arr);
          
              int mode = 0;
              int c = 0;
              int res = 0;
              for(int i =0; i < n-1 ; i++){
                  int count =0;
                  for(int j=1; j < n; j++){
          
                      if(arr[i]==arr[j]){
                          count++;
                          c = arr[i];
                      }
                      if(mode<=count){
                          mode = count;
                          res =c;
                      }
          
                      else{
          
                          continue;
                      }
                  }
          
              }
              if(mode>1) return res;
              else return arr[0];
          
          
          }
          

          }

          • + 0 comments

            Please tell me what's the problem in thus??? Please!!!

        • + 0 comments

          bohot hi easy solution batadiya bhai aap ne thank u

        • + 0 comments

          cool code with great time complexity

    • + 1 comment

      Hello, i'am tring your solution in my machine, but i get error message from the compiler :

      3 12 22 24 Traceback (most recent call last): File "meanMedianMode.py", line 5, in numbers = [list(map(int, input().split()))] File "", line 1 12 22 24 ^ SyntaxError: invalid syntax

      I already trying to figure out what is wrong with this code but i'am still can not found the bugs. May you help me ?

      • + 2 comments

        take out the square brackets [] from around the list() call. It will already return a list and asign it to the numbers variable.

        It is expecting valid list comprehension syntax.

        List comprehensions are a super cool part of python.

        # example
        
        # You can use a loop to create a list
        squares = []
        
        for x in range(10):
            squares.append(x**2)
         
        print squares
        [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
        
        # Or you can use list comprehensions to get the same result:
        squares = [x**2 for x in range(10)]
        
        print squares
        [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
        
        • + 0 comments

          Cool,, thank you for your advise ;)

        • + 3 comments

          hey can u plz tell me how it solves that part where smallest no. should be printed when we have more than one modes??

          • + 0 comments

            it stores the frequency of occuring of different elements at the respective indices and we start finding out the maximum number of times a number has repeated and use that index to print the number

          • + 0 comments
    • + 3 comments

      Why use numpy and scipy when standard lib has statistics?

      • + 0 comments

        Why not to use numpy and scipy?

      • + 1 comment

        @larry_dennis, were you able to get a valid mode from the sample case using the standard library? I was not. Please share if you did.

        • + 2 comments

          Yes i was able to get valid Mode Median and Mean without using NumPy and SciPy, it passes all the listed test cases at least :P

          Can't post the code here as it will defeat the purpose of this Excercise, if you have some specific doubt let me know and i will try to do my best to clear it.

          • + 0 comments

            I am not getting the mode if there does not exist a unique mode using the standard library.

      • + 3 comments

        statistics.mode(data)

        Return the most common data point from discrete or nominal data. The mode (when it exists) is the most typical value, and is a robust measure of central location.

        If data is empty, or if there is not exactly one most common value, StatisticsError is raised.

        mode assumes discrete data, and returns a single value. This is the standard treatment of the mode as commonly taught in schools:

        >>> mode([1, 1, 2, 3, 3, 3, 3, 4])
        3
        

        Source

        • + 1 comment

          I just added a try and except for this

          try: mode = st.mode(mylist) except: mode = min(mylist)

          • + 1 comment

            I did this, but it fails the last hidden test. I cannot figure out why

            import statistics 
            
            N = int(input())
            X = list(map(int, input().split()))
            
            mean = statistics.mean(X)
            median = statistics.median(X)
            
            def mode(sample):
                try:
                    return statistics.mode(sample)
                except:
                    return min(sample)
            
            mode = mode(X)
            
            print("{:.1f}".format(mean))
            print("{:.1f}".format(median))
            print(mode)
            

            print("{:.1f}".format(mean)) print("{:.1f}".format(median)) print(mode)

            • + 0 comments

              In the Except block, You are trying to find the minimum value of the list. But you forgot one condition. What if your testcase has few elements with same number of occurance. For example,

              X = [1,11,3,4,4,5,5,7,7,50]

              Here, 4,5,7 all these three elements have same number of occurance.

              We need to print the 4. But your program prints 1.

        • + 1 comment

          You can do so with Counter from collections in order to take care of mode with standard libs while avoiding the StatisticsError potential of being raised that comes from statistics version of mode:

          from collections import Counter
          
          numbers = [ 1, 1, 2, 2, 3, 3, 4, 1, 2 ]
          mode = Counter(sorted(numbers)).most_common(1)[0][0]
          

          EDIT: Actually, this can be done without collections easily too:

          numbers = [ 1, 1, 2, 2, 3, 3, 4, 1, 2 ]
          mode = max(sorted(numbers), key=numbers.count)
          

          sorted(numbers) is used to ensure that the lowest value most-common number is selected.

          • [deleted]
            + 1 comment

            can you explain "key=numbers.count" code ?

            • + 0 comments

              It is a function to which iterables are passed and the comparison is done based on the value returned by this (here numbers.count which count how many 1, 2, 3(elements in list) etc are present in numbers list) function. Maximizing numbers on the basis of count.

        • + 1 comment
          [deleted]
    • + 1 comment

      Yeah, but trying to do it without import is also cool for learning.

      • + 0 comments

        True, what i learned in the 40 lines of code to do it without importing any package or using any predefined functions in python was worth it.

    • + 2 comments

      What is "size = int(input())" for? Apprently, the submission failed without this line of code, but I don't understand why. Please inform.

      • + 0 comments

        It's to store the initial input :) The problem provides two inputs, even though we run all our analysis off the second input, we need to store the first input, which is the "number of elements," or the size.

      • + 0 comments

        This line converts the input from a string into an integer and assigns it to the 'size' variable which determines the array's lenght, but it's actually excessive here.

    • [deleted]
      + 0 comments

      awesome very PYTHONIC code

    • + 0 comments

      lol

    • + 1 comment

      I'm sure this took little time to write, and so if your boss asked you to solve this problem he'd be very happy (bosses never want you to reinvent the wheel). My question is though, what have you learned about stats by doing this? I'd say no more than I learn about cooking when putting a ready-meal in the microwave. My pure C solution took me ages, but if I didn't already know mean/mode/median I sure as hell would now! Not meaning to be offensive by this, perhaps the real question should be is this challenge to learn about stats, or is it to learn about how to code a solution to a stats problem without needing to know anything about stats at all?

      • + 4 comments

        yo are right indeed..! solving with created functions gives no good..my java code is really big but understandable.. { Scanner sc=new Scanner(System.in); int a=sc.nextInt(); double mean; int[]arr=new int[a]; for(int i=0;i

         }
                  int sum=0;
                 //mean
                  for(int i=0;i<a;i++)
                      {
                      sum=sum+arr[i];
                  }
                  mean=(double)sum/a;
                //median
                  Arrays.sort(arr);
                  double median;
                  int A=arr.length;
                  if(A%2==1)
                  {
                    median=arr[(A-1)/2];
                  }
                  else{
                      int c,d;
                      c=arr[(A-1)/2];
                      d=arr[((A-1)/2)+1];
                      median=(double)(c+d)/2;
                  }
                  //mode
                  int mode=0; int itr; int count;  int max=0;
                  for(int i=0;i<a;i++)
               {
                   itr=arr[i];
                   count=0;
                  for(int c=0;c<a;c++)
                  {
                  if(itr==arr[c])
                  {count++;}
                  if(count>max)
                   {  max=count;
                      if(max==1)
                          {
                          mode=arr[0];
                          }
                     mode=itr;
                        }
                  }           
               }
                  System.out.println(mean);  
                  System.out.println(median);
                  System.out.println(mode);
        
            }
        
        • + 0 comments

          if(max==1){mode=arr[0]} is not necessary, It can run without that its extra burden on compiler

        • + 0 comments

          simple & clear

        • + 0 comments

          import java.io.; import java.util.; import java.util.ArrayList; import java.util.Collections; public class Solution {

          public static void main(String[] args) {
              /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
              Scanner sc= new Scanner(System.in);
              ArrayList<Double> list=new ArrayList<Double>();
              double sum=0, mean=0,median=0, mode;
              int n,c,max=0;
              double v;
              n=sc.nextInt();
              for(int i=0;i<n;i++)
              {
                  v=sc.nextDouble();
                  sum+=v;
                  list.add(v);
              }
          
              mean=(double) sum/n;    
               Collections.sort(list);
               int a=n-1;
                          if(n%2==0)
              {
              median=(list.get((a/2))+list.get((a/2)+1))/2;
              }
              else
              {
                  median=(list.get(a/2))/2;
              }
          
              mode=list.get(0);
              for(int j=0;j<n;j++)
              {
                  double itr=list.get(j);
                  c=0;
                for(int k=0;k<n;k++)
                {
                    if((itr==list.get(k)))
                    {
                    c++;
                if(c>max)
                {max=c;
                if(max==1)
                {
                    mode=list.get(0);
                }
                mode=itr;
                }
                    }
                }
              }
              System.out.println(mean);
              System.out.println(median);
              System.out.println((int)mode);
              sc.close();
              }
          }
          
        • + 1 comment

          can u write in python

          • + 1 comment
            # Enter your code here. Read input from STDIN. Print output to STDOUT
            
            a = int(input())
            numbers = list(map(int, input().split(" ")))
            numbers.sort();
            maxq=1
            currentMax=1
            flag=0
            mode=numbers[0]
            mean = sum(numbers)/a
            if a%2==0:
                median = (numbers[a//2]+numbers[(a//2)-1])/2
            else :
                median = numbers[(a//2)+1]
            for i in range(1, len(numbers)-1):
                if(numbers[i] == numbers[i-1]):
                    maxq=maxq+1
                    if maxq > currentMax:
                      mode =numbers[i]
                      flag=1
                else:
                    if flag == 1:
                     currentMax = maxq
                     flag =0
                    maxq=1
            
            print(mean)
            print(median)
            print(mode)  
            
            • + 0 comments

              else : median = numbers[(a//2)+1] ===> should be numbers[(a//2)] right?

    • + 1 comment

      Could someone explain to me why this returns the smallest number for the mode when all the numbers are only repeated once?

      • + 0 comments

        As you sorted the entire array,the first value encountered while calculating the mode is the smallest value.

    • + 0 comments

      Hi, I didn't understand how size variable effects output even though not seems to be used. I assume its use is hidden because when I changed the name it still runs but when I remove it, there is an error. Thanks for the code!

    • + 1 comment
      [deleted]
    • + 0 comments

      What did you learn? Name of methods which just corressponds to the name of statistic functions we wanted to perform?

    • + 0 comments

      That's awesome! I didn't even think of using numpy!

    • + 2 comments

      Did your code pass test case 3?

      • + 2 comments

        I can't get my code to pass test case 3. It does pass test cases 1, 2, and 4 however

        • + 1 comment

          I have the same problem ..

          • + 0 comments

            Me too. I have build a work around to check if it's test case 3 xD. I fail at the median.

        • + 0 comments

          me too, though i unlocked the 3 test cases and put it to manual test, it works. this is so weird

    • + 0 comments

      numpy is definitley the goto answer, but it just feels like cheating! Haha. But yeah, this is probably the most pythonic.

    • + 0 comments

      Can someone explain this code ?

    • + 0 comments

      Why there's no need to round the mean and median to 1 decimal place?

    • + 0 comments

      That won't work in Hackerrank.

    • + 0 comments

      Can anyone tell me why "size = int(input())" has to be there for the answer to be correct?

    • + 0 comments

      instead of int, i think you have to use float

    • + 0 comments

      Sorry, I'm kindof a beginner, what would be the complexity of this? And how would I even figure that out myself? Just looking up each different function?

      Thanks!

    • + 0 comments

      import numpy as np from scipy import stats

      size = int(input())

      numbers = list(map(int, input().split())) print(np.mean(numbers)) print(np.median(numbers))

      try: print(int(stats.mode(numbers))) except: print(min(numbers))

    • + 0 comments

      where you used size in your code

    • + 0 comments

      Can you please explain how does this take 10 numbers? I dont understand how this works here because when l try to run it on console it stops after taking 1 input.

    • + 0 comments

      script kiddie

    • + 1 comment

      HackerRank begineer here, didn't know you can import external libs before. What libs do I can/cannot import into the HackerRank python intrepreter? thanks for the advice!

      • + 0 comments

        Hi there; You can import most known libs like numpy.

    • + 1 comment

      sorry what is the 0 for in the last line

      • + 0 comments

        I assume this is the line you are talking about - print(int(stats.mode(numbers)[0]))

        Given a list of numbers [1, 1, 1, 2, 2], the mode method in stats package has an output like this:

        ModeResult(mode=array([1]), count=array([4]))

        the print method asks to output the first array in an integer form.

    • + 0 comments

      Whats the point of doing this way if you can use inbuilt functions!

    • + 1 comment

      can you tell me what * [0]* does in

      print(int(stats.mode(numbers)[0]))

      • + 0 comments

        Given a list of numbers [1, 1, 1, 2, 2], the mode method in stats package has an output like this:

        ModeResult(mode=array([1]), count=array([4]))

        the print method asks to output the first array in an integer form.

    • + 0 comments

      My Solution @ Java 8

      import java.io.*;
      import java.util.*;
      
      public class Solution {
      
          private static Scanner scanner = new Scanner(System.in);
          
          public static void main(String[] args) {
              int n = scanner.nextInt();
              scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
      
              int[] arr = new int[n];
      
              String[] arrItems = scanner.nextLine().split(" ");
              scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
      
              for (int i = 0; i < n; i++) {
                  int arrItem = Integer.parseInt(arrItems[i]);
                  arr[i] = arrItem;
              }
      
              scanner.close();
      
              /*Mean*/
              double sum = 0;
              for (int number :
                      arr) {
                  sum += number;
              }
              System.out.println(sum / arr.length);
              /*Median*/
              Arrays.sort(arr);
              double median = 0;
              if (arr.length % 2 == 0) {
                  median = ((double)arr[arr.length/2] + (double)arr[arr.length/2 - 1]) / 2;
              } else {
                  median = arr[arr.length/2];
              }
              System.out.println(median);
              /*Mode*/
              int maxCount = 0;
              int maxValue = 0;
              Arrays.sort(arr);
              for (int number:
                   arr) {
                  int count = 0;
                  for (int innerNumber:
                       arr) {
                      if (number == innerNumber) {
                          ++count;
                      }
                  }
                  if (count > maxCount) {
                      maxCount = count;
                      maxValue = number;
                  }
      
              }
              System.out.println(maxValue);
          }
      }
      
    • + 1 comment

      Why install new packages when you can go with standard Python libraries? Wouldn't this be a better, more portable Python 3? This involves no additional package installs like others are using in their discussion solutions with scipy, numpy, pandas, etc.

      # With standard lib imports only
      from statistics import mean, median
      
      def basicstats(numbers):
          print(round(mean(numbers),1))
          print(median(numbers))
          print(max(sorted(numbers), key=numbers.count))
      
      input() # Don't need array length, so replace var
      numbers = list(map(float, input().split()))
      basicstats(numbers)
      

      EDIT: Removed import of collections, as mode can be done without.

      Of course, if scipy is already included in an application, this isn't an issue.

      Though, introducing additional non-standard packages adds complexity to the supply-chain (includes adding security complexity). For example, this year there was an Arbitrary Code Execution vulnerability associated with numpy that could be remedied only with an update to the package version.

      Installing and depending on third-party packages in Python just because they assist in completing this particular task, when the standard libraries are capable with just as little code, is a problem. Imagine if you were needing to do this same task in an existing application, and a developer said they wanted to introduce scipy (which includes numpy as a dependency) packages in order to get the mode, median, and mean of certain data? Adding two new third-party packages? It's overkill and could be revealing a lack of experience/understanding of standard libraries.

      Installing scipy and numpy adds ~45mb worth of files ( > 3k files) into the project to complete this task, which sounds like overkill.

      • + 0 comments

        Bro you can't just import it is about problem solving not just importing

    • + 0 comments

      Thank you bro !!

    • + 0 comments

      What is the use of this size object that you have created?

    • [deleted]
      + 0 comments

      Hello

      srious.......your code is very elegant Can you explain why did you use [0] in the mode function and how does that work ?

      Thanks Somanshu

    • + 0 comments

      Thank you! Here's my copy, using your solution, but with some refs:

      import numpy as np
      from scipy import stats
      
      n = int(input())
      data = sorted([int(i) for i in input().split()])
      
      data_mean = np.mean(data)
      
      # numpy's median function returns the average of the two medians if our data 
      # has an even number of elements, as required:
      # https://numpy.org/devdocs/reference/generated/numpy.median.html?highlight=median#numpy.median
      data_median = np.median(data)
      
      # https://docs.python.org/3.4/library/statistics.html#statistics.mode
      # "If there is more than one such value, only the smallest is returned"
      data_mode = stats.mode(data)[0][0]
      
      # Print number with one decimal places
      print(data_mean)
      print(data_median)
      print(data_mode)
      
    • + 0 comments

      nice! But need to use float when reading and round the mean and median to 1 decimal - as required by the problem statement

    • + 0 comments

      import numpy as np from scipy import stats

      n=int(input()) s1=input() s2=list(s1.split()) s3=list(map(int,s2))

      print(np.mean(s3),np.median(s3),int(stats.mode(s3)[0]),sep='\n')

    • + 0 comments

      For those getting an error with this code:

      import numpy as np from scipy import stats

      size = int(input()) numbers = list(map(int, input().split())) print(np.mean(numbers)) print(np.median(numbers)) print(*stats.mode(numbers)[0]))

      This unpacks the list element "mode" and prints as an integer value.

    • + 0 comments

      This is a tutorial to understand how these terms work, reinventing the wheel in this particular case is beneficial for building your foundation in statistics. So build the functions yourself;

    • + 0 comments

      Isnt' the idea of this excercise to make you excercise and implement stuff for yourself? And even it's not, isn't it better to do so to better understand the concepts?

    • + 0 comments

      The aim of the question is for you to understand the concept.

    • + 0 comments

      Why you have used [0] here.

    • + 0 comments

      please explain me these 2 lines

      size = int(input()) numbers = list(map(int, input().split()))

    • + 0 comments

      Why stats.mode ??

      /env/python

      import numpy as np

      arr = [input().split()] arr1 = np.array(arr).astype(np.float) index= [0] arr2 = np.delete(arr1,index) print (arr2.mean()) print (arr2.sum()/2) print (arr2.min())

    • + 0 comments

      hoo numpy vibes

    • + 0 comments

      That is pretty good. I knew there were some libraries, but thought it would throw an "module not found" error.

    • + 0 comments

      for code of c++, search my pure basic approach using recent filter

    • + 0 comments

      how is the size var being used here??

    • + 0 comments

      So Damn Awesome..A real help without any stupid complications..

    • + 0 comments

      Please kindly explain:

      why using : size = int(input())
      numbers = list(map(int, input().split()))

      The input first line is N number of elements in the array, and second line is N space-separated integers that describe the array's elements. My understanding is that, if we use int(input()), size will be N+1 as the first line N is an integer in input.

      \\

      Please

    • + 0 comments

      why is "size = int(input())" exist can you explane ?

    • + 0 comments

      The list comp version of map/reduce is also elegant.

      numbers = [int(num) for num in input().split()]
      
    • + 0 comments

      cries in c++

    • + 0 comments

      Python 3: Thanks to srious, wasn't able to figure out how to accept the input. Solution uses only numpy.

      import numpy as np
      
      N=int(input())
      X=list(map(int, input().split()))
      mean=np.mean(X)
      X.sort()
      if N%2!=0:
          median=X[N//2+1]
      else:
          median=np.mean([X[N//2-1],X[(N//2)]])
      v,c = np.unique(X,return_counts=True)
      mode=v[c==c.max()].min()
      
      print("{0:.1f}".format(mean))
      print("{0:.1f}".format(median))
      print("{}".format(mode))