Problem of the Day
A new programming or logic puzzle every Mon-Fri

Mean Median Mode

Classy Tuesday is here! Today's problem is to create a function that takes in a list of integers and prints out the mean, median, and mode. For a bonus also print out the standard deviation.

Permalink: http://problemotd.com/problem/mean-median-mode/

Comments:

  • Johnathan - 10 years, 8 months ago

    Here is my python solution

    num = int(raw_input('How many integers would you like to input? '))
    
    stuff = []
    
    print 'Please enter your integers: '
    
    for i in range(num):
        x = int(raw_input('Integer: '))
        stuff.append(x)
    
    stuff.sort()
    
    
    
    def mean(list): 
        num = len(list)
        value = 0.0
    
        for i in range(num): 
            value = value + list[i]
    
        value = value/num
        return value
    
    def median(list):
        num = len(list)
        value = 0.0
    
        if num % 2 == 0:
            numx = num/2
            value = list[numx-1] + list[numx]
            value = float(value)
            value = value/2
    
        else:
            numx = num + 1
            numx = numx/2
            value = list[numx - 1]
    
        return value
    
    def mode(list):
        num = len(list)
        max = 0
        count = 0
        numbers = []
    
        for i in range(1, num):        
            if list[i] == list[i-1]:
                count = count + 1
    
                if count == max: 
                    numbers.append(list[i])
    
                elif count > max:
                    max = count
                    numbers = []
                    numbers.append(list[i])
            else:
                count = 0
        if max == 0:
            return 'There is no mode.'
        else:
            return numbers
    
    def sd(list):
        num = len(list)
        mean = 0.0
    
        for i in range(num): 
            mean = mean + list[i]
    
        mean = mean/num
    
        total = 0.0
    
        for i in range(num):
            square = list[i] - mean
            square = square * square
            total = total + square
        final = total/num
        final = final**(0.5)
        return final
    
    k = mean(stuff)
    print 'The mean is equal to',k,'.'
    
    k = median(stuff)
    print 'The median is equal to',k,'.'
    
    k = mode(stuff)
    print 'The mode is equal to',k,'.'
    
    k = sd(stuff)
    print 'The standard deviation is equal to',k,'.'
    
    t = raw_input('')
    

    reply permalink

  • Max Burstein - 10 years, 8 months ago

    Nice!

    reply permalink

  • David - 10 years, 8 months ago

    You can use ** for exponents.

    square**2 == square * square
    

    You can replace duplicating a variable on the operation side with [operand]= [other variable]

    value = value + list[i]
    # ^ becomes:
    value += list[i]
    

    You could also make your setup phase much more flexible by using a while loop instead of asking for the number of integers they want and asking in a for loop. As long as they give you an integer (or a float if you make a function for checking that) you ask for another.

    while(raw_input('[your_string]: ').isdigit()):  
        stuff.append(x)
    

    Although it makes your code look more consistent, you can use a for loop on the list itself rather than on a range. This makes the most sense to point out for your use in mean() and sd() where you are not referencing more than one element per iteration.

    for i in range(num):  
            value = value + list[i]
    

    becomes

    for number in list: 
            value += number
    

    Nice work

    reply permalink

  • Johnathan - 10 years, 8 months ago

    Thanks for the feedback David.

    reply permalink

  • Nick - 10 years, 8 months ago

    Bit late but here's my Java solution:

    import java.util.Collections;
    import java.util.List;
    
    public class MeanMedianMode {
        public static void calculateMeanMedianMode(List<Integer> input) {
            if (input == null || input.size() == 0) {
                System.out.println("Invalid input");
                return;
            }
    
            Collections.sort(input);
    
            Integer sum = 0;
    
            Integer currentRun = 0;
            Integer bestRun = 0;
            Integer mode = null;
    
            Integer lastNum = null;
    
            System.out.print("Ordered input: ");
            for (Integer elem : input) {
                System.out.print(elem + " ");
    
                sum += elem;
    
                if (elem.equals(lastNum)) {
                    currentRun++;
                }
                else {
                    if (currentRun > bestRun) {
                        mode = lastNum;
                        bestRun = currentRun;
                    }
    
                    currentRun = 1;
                }
    
                lastNum = elem;
            }
    
            if (currentRun > bestRun) {
                mode = lastNum;
            }
    
            System.out.println();
    
            Double mean = sum / Double.valueOf(input.size());
            Integer median = input.get(input.size() / 2);
    
            Double standardDeviation = calculateStandardDeviation(input, mean);
    
            System.out.println("Mean is " + mean);
            System.out.println("Median is " + median);
            System.out.println("Mode is " + mode);
            System.out.println("Standard deviation is " + standardDeviation);
        }
    
        private static Double calculateStandardDeviation(List<Integer> list, Double mean) {
            Double sumOfSquares = 0.0;
            for (Integer elem : list) {
                Double difference = elem - mean;
                sumOfSquares += (difference*difference);
            }
    
            return Math.sqrt((1D / list.size()) * sumOfSquares);
        }
    }
    

    reply permalink

Content curated by @MaxBurstein