# Program to find total duration of K most watched shows in Python

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

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

• i := i + 1

## 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
while i < k:
i += 1

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