Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
walrus operator and creative use of boolean solution in Clear category for Lightbulb End Watching by leggewie
from datetime import datetime, timedelta
from typing import List, Optional
# massively inspired by the awesome code from eugene100372
# https://py.checkio.org/mission/lightbulb-start-watching/publications/eugene100372/python-3/first/
def sum_light(els: List[datetime], start_watching: Optional[datetime] = None, end_watching: Optional[datetime] = None) -> int:
"""
how long the light bulb has been turned on
"""
if len(els)%2>0: els.append(end_watching) # make sure to stop even if no final button press recorded
if not (sw:=start_watching): sw=els[0] # make sure to start no earlier than start_watching
if not (ew:=end_watching): ew=els[-1] # make sure to stop no later than end_watching
seconds = sum(
((off-sw)*(off>sw)-(on-sw)*(on>sw)-(off-ew)*(off>ew)+(on-ew)*(on>ew)).total_seconds()
for on,off in zip(els[0::2],els[1::2])
)
return seconds
May 31, 2021