We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
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];
}
List comprehensions are a super cool part of python.
# example# You can use a loop to create a listsquares=[]forxinrange(10):squares.append(x**2)printsquares[0,1,4,9,16,25,36,49,64,81]# Or you can use list comprehensions to get the same result:squares=[x**2forxinrange(10)]printsquares[0,1,4,9,16,25,36,49,64,81]
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
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.
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:
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.
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:
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.
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.
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.
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?
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);
}
# Enter your code here. Read input from STDIN. Print output to STDOUTa=int(input())numbers=list(map(int,input().split(" ")))numbers.sort();maxq=1currentMax=1flag=0mode=numbers[0]mean=sum(numbers)/aifa%2==0:median=(numbers[a//2]+numbers[(a//2)-1])/2else:median=numbers[(a//2)+1]foriinrange(1,len(numbers)-1):if(numbers[i]==numbers[i-1]):maxq=maxq+1ifmaxq>currentMax:mode=numbers[i]flag=1else:ifflag==1:currentMax=maxqflag=0maxq=1print(mean)print(median)print(mode)
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!
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?
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.
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!
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 onlyfromstatisticsimportmean,mediandefbasicstats(numbers):print(round(mean(numbers),1))print(median(numbers))print(max(sorted(numbers),key=numbers.count))input()# Don't need array length, so replace varnumbers=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.
Thank you! Here's my copy, using your solution, but with some refs:
importnumpyasnpfromscipyimportstatsn=int(input())data=sorted([int(i)foriininput().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.mediandata_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 placesprint(data_mean)print(data_median)print(data_mode)
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;
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?
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.
Day 0: Mean, Median, and Mode
You are viewing a single comment's thread. Return to all comments →
Python 3 - Dont reinvent the wheel ;)
lol this is so elegant
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
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
https://infosecgeek107746281.wordpress.com/2020/10/01/mean-median-mode-challenge-hackerrank/ or read from here
Here is my simple answer using java language
Your median assumes an array with even number length.
how did you think the logic for the mode function??
import java.io.; import java.util.; import java.text.; import java.math.; import java.util.regex.*;
public class Solution {
}
Please tell me what's the problem in thus??? Please!!!
bohot hi easy solution batadiya bhai aap ne thank u
cool code with great time complexity
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 ?
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.
Cool,, thank you for your advise ;)
hey can u plz tell me how it solves that part where smallest no. should be printed when we have more than one modes??
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
Why use numpy and scipy when standard lib has statistics?
Why not to use numpy and scipy?
@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.
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.
I am not getting the mode if there does not exist a unique mode using the standard library.
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:Source
I just added a try and except for this
try: mode = st.mode(mylist) except: mode = min(mylist)
I did this, but it fails the last hidden test. I cannot figure out why
print("{:.1f}".format(mean)) print("{:.1f}".format(median)) print(mode)
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.
You can do so with
Counter
from collections in order to take care of mode with standard libs while avoiding theStatisticsError
potential of being raised that comes fromstatistics
version ofmode
:EDIT: Actually, this can be done without
collections
easily too:sorted(numbers)
is used to ensure that the lowest value most-common number is selected.can you explain "key=numbers.count" code ?
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.
Yeah, but trying to do it without import is also cool for learning.
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.
What is "size = int(input())" for? Apprently, the submission failed without this line of code, but I don't understand why. Please inform.
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.
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.
awesome very PYTHONIC code
lol
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?
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
if(max==1){mode=arr[0]} is not necessary, It can run without that its extra burden on compiler
simple & clear
import java.io.; import java.util.; import java.util.ArrayList; import java.util.Collections; public class Solution {
can u write in python
else : median = numbers[(a//2)+1] ===> should be numbers[(a//2)] right?
Could someone explain to me why this returns the smallest number for the mode when all the numbers are only repeated once?
As you sorted the entire array,the first value encountered while calculating the mode is the smallest value.
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!
What did you learn? Name of methods which just corressponds to the name of statistic functions we wanted to perform?
That's awesome! I didn't even think of using numpy!
Did your code pass test case 3?
I can't get my code to pass test case 3. It does pass test cases 1, 2, and 4 however
I have the same problem ..
Me too. I have build a work around to check if it's test case 3 xD. I fail at the median.
me too, though i unlocked the 3 test cases and put it to manual test, it works. this is so weird
numpy is definitley the goto answer, but it just feels like cheating! Haha. But yeah, this is probably the most pythonic.
Can someone explain this code ?
Why there's no need to round the mean and median to 1 decimal place?
That won't work in Hackerrank.
Can anyone tell me why "size = int(input())" has to be there for the answer to be correct?
instead of int, i think you have to use float
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!
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))
where you used size in your code
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.
script kiddie
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!
Hi there; You can import most known libs like numpy.
sorry what is the 0 for in the last line
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.
Whats the point of doing this way if you can use inbuilt functions!
can you tell me what * [0]* does in
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.
My Solution @ Java 8
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.
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 includesnumpy
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
andnumpy
adds ~45mb worth of files ( > 3k files) into the project to complete this task, which sounds like overkill.Bro you can't just import it is about problem solving not just importing
Thank you bro !!
What is the use of this size object that you have created?
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
Thank you! Here's my copy, using your solution, but with some refs:
nice! But need to use float when reading and round the mean and median to 1 decimal - as required by the problem statement
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')
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.
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;
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?
The aim of the question is for you to understand the concept.
Why you have used [0] here.
please explain me these 2 lines
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())
hoo numpy vibes
That is pretty good. I knew there were some libraries, but thought it would throw an "module not found" error.
for code of c++, search my pure basic approach using recent filter
how is the size var being used here??
So Damn Awesome..A real help without any stupid complications..
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
why is "size = int(input())" exist can you explane ?
The list comp version of map/reduce is also elegant.
cries in c++
Python 3: Thanks to srious, wasn't able to figure out how to accept the input. Solution uses only numpy.