Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
array of lamps and array of event solution in Clear category for Multiple Lightbulbs by kdim
from datetime import datetime
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] = None) -> int:
els = [list(els[i]) if type(els[i]) == tuple else [els[i], 1] for i in range(len(els))] # normalization of els
start = start_watching if start_watching else els[0][0]
end = end_watching if end_watching else els[-1][0]
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] #
]
lamps = [False] * max(els, key=lambda x: x[1])[1] # array of lamps
for i, d in enumerate(els):
lamps[d[1]-1] = not lamps[d[1]-1] # push button
light += [[d[0], any(lamps)]] # add event and True for light On
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]] # sum if before was True (light On)
return sum(delta)
Jan. 17, 2021
Comments: