## Calculating Statistics

### October 4, 2013

In today’s exercise we will do somebody’s homework:

Read a file containing integers, one integer per line. At the end of the file, write the number of integers in the file, their sum, and the mean, median, mode, minimum and maximum of the integers in the file.

Your task is to write the indicated program. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

Advertisements

Pages: 1 2

The median for the list of numbers in the example is 6, not 5.

In Python.For the median I use: middle element if odd number of elements, else average of middle 2 elements.

Nothing special. Ruby.

It’s tricky to determine the “best” approach without some knowledge of the expected data.

Only a few dozen values, and all values are less than a thousand? Just read them all into an array of regular old integers, and do the math afterwards. The code will be simple, easy to read, and easy to maintain.

Tens of millions of values? You might want to do something more clever, like keep a running total of count, total, min and max, and then do some hashtables for frequency (for the mode) and .. I don’t know, maybe some clever post-processing with the frequency tables for the median.

Values could be > 4,294,967,295? Then you need to do some careful thinking. :0)

But if you can be reasonably confident the values will be small enough (and few enough) that their sum fits comfortably in a regular old integer, and if the code is unlikely to be run more than a few dozen times on any given day, then I’d suggest the seasoned veteran programmer would take the simple approach and reduce the maintenance burden.