Lots of comments, not much code solution in Clear category for Lightbulb End Watching by new_hoschi
from datetime import datetime,timedelta
from typing import List, Optional
def sum_light(els: List[datetime], start_watching: Optional[datetime] = None, end_watching: Optional[datetime] = None) -> int:
''' 1. Preprocess list, i.e. manipulate the start, such that the first
element is either "start_watching" or the element of the list
following the event "start_watching". Snip off the unnecessary elements
of the list.
Do a similar algorithm to process the end_watching event.
2. Take pairs of elements of the given list (light on and light off event),
calculate a timedelta element, giving years,seconds,milliseconds of the
time the light is switched on, use the method "total_seconds()" to
convert it to seconds only and finally add these values and obtain the
total time of light being switched on.
# Part 1:
# minidx will be the minimal index where the corresponding list element
# is later in time than "start_watching"
# i.e. the light is on at the event "start_watching", this is
# because the index of the next element of the list is odd
# (light on: index 0,2,4 etc., light off: index 1,3,5).
if maxidx == len(els):
## there is the case, where the light remains permanently on
## (odd number of elements in the list), then we need to add the
## stoping event to the end of the list. nothing to do, when there
## is an even number of elements and end_watching comes after the
## final list element (light is off, there is nothing to count)
# Part 2:
clicks=len(els)//2 # number of on AND OFF-clicks of the switch
return sum((els[2*on+1]-els[2*on]).total_seconds() for on in range(clicks))
Jan. 26, 2021