An Irish Rail journey log has gaps. What counts when you work out the mean?
You've logged your Irish Rail journey times to see how long the trip usually takes. Some rows have a time in minutes, and some are blank. When your program works out the mean, should those blank rows count as journeys?
Start with the raw journey log. Your cleaning rules tell you which times to keep. In a frequency algorithm, you started a counter at zero and added one for each match. Reuse that idea here: add one for every time you keep.
Set the total to zero, then the count to zero. For the eight-minute reading, the total becomes eight and the count becomes one. For the fourteen-minute reading, the total becomes twenty-two and the count becomes two. The sum so far is your running total.
Your running total is thirty minutes from two valid readings. The next valid journey took eighteen minutes. What should the total and the count be after you process that reading? Pick the pair that updates both values correctly.
Take three valid times: twelve, seventeen and nineteen minutes. Start both values at zero. Add twelve: the total is twelve and the count is one. Add seventeen: twenty-nine and two. Add nineteen: forty-eight and three. Divide the total, forty-eight, by the included count, three, to get sixteen minutes.
Your file has four rows: nine minutes, a blank, fourteen minutes and thirteen minutes. The cleaning rules exclude the blank. What mean should your program calculate? Pick the answer that uses only the readings you included.
After the loop, pass the total and count to this function. If the count is zero, return None to signal there is no mean. Otherwise, divide the total by the count. For a group with two blank rows, both values stay at zero, so the call returns None without dividing.
Both columns show the same rows: eighteen minutes, a blank and twenty-four minutes. The valid times add to forty-two minutes. If you count all three rows, you get fourteen minutes, as if the blank were a zero-minute trip. Count only the two valid times and the mean is twenty-one minutes.
Suppose the three times you traced were morning journeys and the last file recorded evening journeys. On the same scale, the morning mean is sixteen minutes and the evening mean is twenty-one. Investigate the evening group first if you're looking for longer trips. A group with no mean gets no bar.
Write an algorithm to calculate the mean of the valid journey times. Here, blanks are stored as None and all other entries are valid. Start both variables at zero. Update them inside the loop only for valid times. After the loop, check for zero before dividing by the included count.