Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Chương trình tìm tổng thời lượng K chương trình xem nhiều nhất trong Python

Cho danh sách shows (tên chương trình), durations (thời lượng), và số k. Mỗi cặp shows[i], durations[i] là một lần xem. Tìm tổng thời lượng của k chương trình được xem nhiều nhất (tổng thời lượng xem).

Ví dụ: shows = ["The BGT", "Jack jumper", "The BGT", "Jokers Company", "Music magic"], durations = [10, 8, 10, 18, 9], k = 2 → kết quả 38. Top 2: "Jokers Company" (18) + "The BGT" (10+10=20) = 38.

Thuật toán giải quyết

  1. Dùng defaultdict(int) gom tổng thời lượng theo tên show
  2. Lấy các giá trị tổng, sắp xếp giảm dần
  3. Cộng k giá trị đầu tiên

Ví dụ minh họa

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 = list(d.values())
    l.sort(reverse=True)
    answer = 0
    for i in range(k):
        answer += l[i]
    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))

Đầu vào

["The BGT", "Jack jumper", "The BGT", "Jokers Company", "Music magic"], [10, 8, 10, 18, 9], 2

Đầu ra

38