 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to find number of K-Length sublists whose average is greater or same as target in python
Suppose we have a list nums, and two additional values k and target, we have to find the number of sublists whose size is k and its average value ≥ target.
So, if the input is like nums = [1, 10, 5, 6, 7] k = 3 target = 6, then the output will be 2, as the sublist [1, 10, 7] has average value of 6 and [10, 5, 6] has average of 7.
To solve this, we will follow these steps:
- target := target * k
- sum := 0, ans := 0
- for each index i and number n in nums, do- if i >= k, then- sum := sum - nums[i - k]
 
- sum := sum + n
- if i >=(k - 1) , then- if sum >= target, then- ans := ans + 1
 
 
- if sum >= target, then
 
- if i >= k, then
- return ans
Let us see the following implementation to get better understanding:
Example Code
class Solution: def solve(self, nums, k, target): target *= k sum = 0 ans = 0 for i, n in enumerate(nums): if i >= k: sum -= nums[i - k] sum += n if i >= (k - 1): if sum >= target: ans += 1 return ans ob = Solution() nums = [1, 10, 5, 6, 7] k = 3 target = 6 print(ob.solve(nums, k, target))
Input
[1, 10, 5, 6, 7], 3, 6
Output
2
Advertisements
 