 
  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 total duration of K most watched shows in Python
Suppose we have a list of list of strings called shows, also have a list of integers called durations, and another value k, here shows[i] and durations[i] represent a show and its duration watched by the ith man, we have to find the total duration watched of the k most watched shows.
So, if the input is like shows = ["The BGT", "Jack jumper", "The BGT", "Jokers Company", "Music magic"] durations = [10, 8, 10, 18, 9] k = 2, then the output will be 38, as the top 2 most watched shows are "Jokers Company" and "The BGT" and total durations is 18 and 10 + 10 = 20.
To solve this, we will follow these steps −
-  if shows is empty or durations is empty or k is 0, then - return 0 
 
- d := an empty dictionary 
-  for i in range 0 to size of shows, do - d[shows[i]] := d[shows[i]] + durations[i] 
 
- l := a new list 
-  for each i in d, do - insert d[i] at the end of l 
 
- sort the list l in reverse order 
- i := 0 
- answer := 0 
-  while i < k, do - answer := answer + l[i] 
- i := i + 1 
 
- return answer 
Example
Let us see the following implementation to get better understanding
from collections import defaultdict def solve(shows, durations, k): if not shows or not durations or not k: return 0 d = defaultdict(int) for i in range(len(shows)): d[shows[i]] += durations[i] l = [] for i in d: l.append(d[i]) l.sort(reverse=True) i = 0 answer = 0 while i < k: answer += l[i] i += 1 return answer shows = ["The BGT", "Jack jumper", "The BGT", "Jokers Company", "Music magic"] durations = [10, 8, 10, 18, 9] k = 2 print(solve(shows, durations, k))
Input
["The BGT", "Jack jumper", "The BGT", "Jokers Company", "Music magic"], [10, 8, 10, 18, 9], 2
Output
38
