Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
8 lines proc solution in Creative category for Lightbulb Operating by CDG.Axel
from datetime import datetime, timedelta
from typing import List, Optional, Union, Tuple
def sum_light(els: List[Union[datetime, Tuple[datetime, int]]],
start_watching: Optional[datetime] = None,
end_watching: Optional[datetime] = datetime(9999,12,31),
operating: Optional[timedelta] = None) -> int:
"""
how long the light bulb has been turned on
"""
# replace elements with no bulb index, add max date for count light after last interval
els = sorted([(e, 0) if type(e) is datetime else e for e in els])+[(end_watching, 0)]
# make all interaval to be (start_watching <= time <= end_watching)
els = [(min(end_watching, max(t, start_watching or t)), s) for t, s in els]
# init ramain time for each lamp
remain, switch, time_on = [operating.total_seconds() if operating else 1e10] * 10, [False] * 10, 0
for i, (t, l) in enumerate(els):
interval = (t - els[i-1][0]).total_seconds() if i else 0
# light time is max time of each switched lamp, limited by remained time
time_on += max([min(remain[j], interval) for j, cs in enumerate(switch) if cs], default=0)
# reduce remained tme for switched lamp, invert switch
remain, switch[l] = [r - min(r, interval) * switch[j] for j, r in enumerate(remain)], not switch[l]
return time_on
Nov. 23, 2021
Comments: