Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Function to trim a list and calculate mean of remaining numbers

I need a function that takes a list of numbers as the input and an optional integer keyword argument trim (that takes on values of 0 or larger).

  1. I want to remove the largest and smallest numbers from the list
    and
  2. Return the mean of the numbers left.

However, I keep getting errors. I am a beginner and have no clue how to fix it.

Here is what I have tried:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

def trimmed_mean (lst, trim):
    trimmed_mean.sort()
    if trimmed_mean.remove(max) and trimmed_mean.remove(min):
        return trimmed_mean 
    else: 
        return None

Could someone please help me find my mistake, please? Thanks!

>Solution :

First, you should call the list methods on lst, not the function name. Second, min() and max() are built-in functions, and require an iterable as paramerer. However, you wouldn’t need them since your list is already sorted and has the minimal and maximal values at each end:

def trimmed_mean(lst, trim):
    if len(lst) < 3:          # guard clause if trimmed list would be empty
        return None
    lst = sorted(lst)[1:-1]   # sort list and splice from second index to second-to-last index
    return sum(lst)/len(lst)  # calculate and return mean

Good to mention: lst.sort() sorts the list in place and doesn’t return anything. sorted(lst) returns the sorted list and doesn’t affect the original.

Without sorting, you can use the min() and max() functions like so:

def trimmed_mean(lst, trim):
    if len(lst) < 3:              # guard clause if trimmed list would be empty
        return None
    min_i = lst.remove(min(lst))
    max_i = lst.remove(max(lst))
    return sum(lst)/len(lst)

Finally, if the trim parameter indicates the number of minimal and maximal values to be trimmed, I would use this function:

def trimmed_mean(lst, trim):
    if len(lst) < (trim*2)+1:          # guard clause if trimmed list would be empty
        return None
    lst = sorted(lst)[trim:-trim]   # sort list and splice from second index to second-to-last index
    return sum(lst)/len(lst)  # calculate and return mean
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading