Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

โปรแกรมหา Duration รวมของ K รายการที่ดูมากที่สุดใน Python

ให้ลิสต์ shows (ชื่อรายการ) และ durations (ระยะเวลา) หา Duration รวมของ Top-K รายการที่ถูกดูมากที่สุด (รวม Duration ต่อ Show)

ตัวอย่าง: shows=["The BGT","Jack jumper","The BGT","Jokers Company","Music magic"], durations=[10,8,10,18,9], k=2 → 38 (Jokers Company:18, The BGT:20)

ขั้นตอน

  1. รวม Duration ต่อ Show ด้วย Dictionary
  2. เรียงค่า Duration จากมากไปน้อย
  3. รวม k อันแรก

ตัวอย่างโค้ด

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 = sorted(d.values(), reverse=True)
    return sum(l[:k])

shows = ["The BGT", "Jack jumper", "The BGT", "Jokers Company", "Music magic"]
durations = [10, 8, 10, 18, 9]
k = 2
print(solve(shows, durations, k))  # Output: 38

อินพุต

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

เอาต์พุต

38