我正在编写一个程序,我需要计算一部电影的总观看时间。
1st watch = (0,10)
2nd Watch =(13,18)
3rd watch =(15,23)
4th watch =(21,26)
观看的电影总数= 10 + 5 + 5 + 3 = 23分钟
我如何在Python中实现它
答案 0 :(得分:1)
好的,这里真正的挑战是重叠序列。抱歉,你的问题不是很清楚。
这不是最佳的(请参阅下面的更好算法),但您可以尝试:
l = [(0, 10), (13, 18), (15, 23), (21, 26)]
s = set()
for w in l:
s = s.union(range(*w))
d = len(s)
它应该做的伎俩。它给出d = 23。
编辑:更好的算法
l = [(0, 10), (13, 18), (15, 23), (21, 26)]
flat_list = sorted([(t[0], 1) for t in l] + [(t[1], -1) for t in l])
# flat_list == [(0, 1), (10, -1), (13, 1), (15, 1), (18, -1), (21, 1), (23, -1), (26, -1)]
duration = level = 0
start = None
for minute, level_inc in flat_list:
level += level_inc
if level == 0:
duration += minute - start
start = None
elif start is None and level == 1:
start = minute
assert(level == 0) # something is wrong otherwise
print("Duration is {}".format(duration))