Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
10 lines, commented solution in Clear category for Lightbulb Operating by CDG.Axel
# Taken from mission Multiple Lightbulbs
from datetime import datetime, timedelta
from typing import List, Optional, Union, Tuple
from operator import itemgetter
def sum_light(els: List[Union[datetime, Tuple[datetime, int]]],
start_watching: Optional[datetime] = None,
end_watching: Optional[datetime] = None,
operating: Optional[timedelta] = None) -> int:
"""
how long the light bulb has been turned on
"""
# replace elements with no bulb index and sort the list
els, time_on = sorted([(e, 0) if type(e) is datetime else e for e in els]), 0
# make end watching not null
ew, switch = end_watching or els[-1][0], [False] * 10
# init remaining time for lamps, add end watching element to main list
remain, els = [operating.total_seconds() if operating else 1e10] * 10, els + [(ew, 0)]
# count on time for each interval
for i, e in enumerate(els):
# put time in range from sw to ew
els[i] = min(ew, max(e[0], start_watching or e[0]))
interval = (els[i] - els[i - 1]).total_seconds() if i else 0
# calculate time of powered lamps (switch = True), limited by remaining time of lamp
time_on += max([min(remain[j], interval) for j, cs in enumerate(switch) if cs], default=0)
# then decrease time for powered lamp
remain = [r - min(r, interval) * switch[j] for j, r in enumerate(remain)]
# invert switch after count current interval
switch[e[1]] = not switch[e[1]]
return time_on
print("The forth mission in series is completed? Click 'Check' to earn cool rewards!")
Oct. 31, 2021
Comments: