在 Python 中查找 K 个最受关注节目的总时长的程序
假设我们有一个名为shows的字符串列表,还有一个名为durations的整数列表,还有另一个值k,这里shows[i]和durations[i]代表第i个人观看的节目及其持续时间,我们有找出观看次数最多的k个节目的总观看时长。
因此,如果输入类似于shows=["TheBGT","Jackjumper","TheBGT","JokersCompany","Musicmagic"]持续时间=[10,8,10,18,9]k=2,那么输出将是38,因为前2个最受关注的节目是“JokersCompany”和“TheBGT”,总时长为18和10+10=20。
示例
让我们看下面的实现来更好地理解
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))
输入
["The BGT", "Jack jumper", "The BGT", "Jokers Company", "Music magic"], [10, 8, 10, 18, 9], 2输出结果
38