pythonjavaaveragepseudocodemoving-average

Is it possible to find the average of a group of numbers and return the index of the number furthest from the average with one loop?


Specifically: Write a function (in python, java or pseudocode) average(nums) that prints the mean of the numbers in list nums, and returns a tuple:

Can this be done with one loop?

I know how to write the function with two loops, and using one or two loops are both O(n) time, so the code doesn't technically become more efficient with one loop. But I'm just curious if it can be done. A party trick, if you will.

Some of my thought process: So computing the average as you iterate through the list is as simple as total += nums[i], then avg = total/(i+1). And I guess you could calculate which number is furthest from your current average, but by the time you get to the end of the list an extreme number could make your code incorrect , I think?


Solution

  • Is it possible to find the average of a group of numbers and return the index of the number furthest from the average with one loop?

    Yes. The number furthest from the mean will be either the largest or the smallest in the sample. With a single pass through the data, you can compute the average and track the indices of the largest and smallest elements seen so far. At the end, you'll know the indices of the overall largest and smallest. You can check which of these is further from the mean, and return the information for that one.