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
if n != mx and n != mn:
. What if all elements are equal to eithermx
ormn
(i.e. if there are only 1 or 2 unique elements)? – Selcuk