Find Mean of Array After Removing Elements in Python



Suppose we have array called nums, we have to find the mean of the remaining values after removing the smallest 5% and the largest 5% of the elements.

So, if the input is like nums = [2,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,8], then the output will be 4.0 because after removing smallest and largest values, all are same, then the median is

To solve this, we will follow these steps −

  • sort the list nums

  • n := size of nums

  • per := quotient of (n*5/100)

  • l2 := subarray of nums from index per to (size of nums - per - 1)

  • x := average of all elements in l2

  • return x

Example (Python)

Let us see the following implementation to get better understanding −

 Live Demo

def solve(nums):    nums.sort()    n = len(nums)    per = int(n*5/100)    l2 = nums[per:len(nums)-per]    x = sum(l2)/len(l2)    return x nums = [2,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,8] print(solve(nums))

Input

[2,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,8]

Output

4.0
Updated on: 2021-05-17T13:07:17+05:30

225 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements
close