Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
add array of light solution in Clear category for Lightbulb End Watching by kdim
from datetime import datetime
from typing import List, Optional
def sum_light(els: List[datetime], start_watching: Optional[datetime] = None, end_watching: Optional[datetime] = None) -> int:
start = start_watching if start_watching else els[0]
end = end_watching if end_watching else els[-1]
light = [ # array with event and True/False if light On/Off
[datetime(1970, 1, 1, 0, 0, 0), False], # initially the light was off ;-)
[datetime(9999, 12, 31, 23, 59, 59), False], # in future the light was off too ;-)
[start, None], # None for Start and End
[end, None] #
]
light += [ [d, not i%2] for i, d in enumerate(els) ] # add event and True for fist push and False for second push button
light = sorted(light, key = lambda x: x[0]) # sorted for time
for i, d in enumerate(light): # replace None with the values that were before
if d[1] == None: light[i][1] = light[i-1][1] #
light = dict(light) # remove duplicates event
light = list(filter(lambda x: start <= x[0] <= end, light.items())) # filter event between start and stop
delta = [(light[i][0]-light[i-1][0]).total_seconds() for i in range(1, len(light)) if light[i-1][1]] # summ if before was True (light On)
return sum(delta)
Jan. 17, 2021