- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Remove One to Make Average k in Python
Suppose we have a list of numbers called nums and an integer k, we have to check whether we can remove exactly one element from the list to make the average equal to exactly k. Now we have to keep in mind that, there are some constraints −
- 2 ≤ n ≤ 1,000 where n is number of elements of nums list
- nums[i], k ≤ 1,000,000
So, if the input is like [5,3,2,4,6,10], k = 4, then the output will be True as if we remove 10, then the average of elements will be (5+3+2+4+6)/5 = 4, this is same as k.
To solve this, we will follow these steps −
- s:= total sum of all elements in nums
- t := k*(size of nums - 1)
- for each i in nums, do
- if s-i is same as t, then
- return True
- if s-i is same as t, then
- return False
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, nums, k): s=sum(nums) t = k*(len(nums)-1) for i in nums: if s-i == t: return True return False ob = Solution() nums = [5,3,2,4,6,10] k = 4 print(ob.solve(nums, k))
Input
[5,3,2,4,6,10], 4
Output
True
Advertisements