0
votes

I'm being asked to: Return the "centered" average of an array of ints, which we'll say is the mean average of the values, except ignoring the largest and smallest values in the array. If there are multiple copies of the smallest value, ignore just one copy, and likewise for the largest value. Use int division to produce the final average. You may assume that the array is length 3 or more.

I'm getting most use cases to return correctly, but I'm getting: Getting ZeroDivisionError: division by zero error on a few cases. Any help would be appreciated.

Note: I'm not allowed to use any imported libraries.

My code:

def centered_average(nums):
    mx = max(nums)
    #print(mx)


    mn = min(nums)
    #print(mx)

    n_lst = []

    for n in nums:
        if n != mx and n != mn:
            n_lst.append(n)

    #print(n_lst)        
    return int(sum(n_lst) / len(n_lst))

use cases I'm getting the error on:

centered_average([1, 1, 100])
centered_average([7, 7, 7])
centered_average([1, 1, 99, 99])
centered_average([4, 4, 4, 4, 5])

ERROR:

ZeroDivisionError: division by zero

1
Re-consider the condition here: if n != mx and n != mn:. What if all elements are equal to either mx or mn (i.e. if there are only 1 or 2 unique elements)?Selcuk
That means that the length of the list is 0. Add an else statement after the append and print 'n' to see what's going on. That will tell you why it's not appending anything. Then, back-track and find out why.STF_ZBR
Ahh yeah, I see that now. Duh. lol Thank you.Justin Reynolds

1 Answers

0
votes

The problem with your code is that if there are multiple occurrences of min or max you neglect all of them unlike your requirement:

ignore just one copy

Use this:

def centered_average(nums):
    n_lst = sorted(nums)[1:-1]
    return sum(n_lst)// len(n_lst)

The code is short and simple. Sort the list, ignore the first and the last values i.e. min and max. Return the average of the obtained list. NOTE: The // sign refers to integer division and saves you from typecasting later.