Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Not the shortest but explained solution in Clear category for Lightbulb Start Watching by Selindian
from datetime import datetime
from typing import List, Optional
def sum_light(els: List[datetime], start_watching: Optional[datetime] = None) -> int:
"""
how long the light bulb has been turned on
"""
result = 0
pairs = zip(els[::2], els[1::2]) # Use zip and slicing to get pairs of els-elements (1,2), (3,4), ...
for on, off in pairs: # Loop over that pairs
if start_watching: # ... If start_watching was passed
if on < start_watching < off: # ... ... if start_watching between on and off
on = start_watching # ... ... ... it becomes our new on
if start_watching >= off: # ... ... if it later than off
continue # ... ... ... continue with next loop as nothing was watched yet
result += (off - on).total_seconds() # ... calculate difference in total seconds; add that to result
return int(result) # return result as integer
if __name__ == "__main__":
print("Example:")
print(
sum_light(
[
datetime(2015, 1, 12, 10, 0, 0),
datetime(2015, 1, 12, 10, 0, 10),
],
datetime(2015, 1, 12, 10, 0, 5),
)
)
assert (
sum_light(
els=[
datetime(2015, 1, 12, 10, 0, 0),
datetime(2015, 1, 12, 10, 0, 10),
],
start_watching=datetime(2015, 1, 12, 10, 0, 5),
)
== 5
)
assert (
sum_light(
[
datetime(2015, 1, 12, 10, 0, 0),
datetime(2015, 1, 12, 10, 0, 10),
],
datetime(2015, 1, 12, 10, 0, 0),
)
== 10
)
assert (
sum_light(
[
datetime(2015, 1, 12, 10, 0, 0),
datetime(2015, 1, 12, 10, 10, 10),
datetime(2015, 1, 12, 11, 0, 0),
datetime(2015, 1, 12, 11, 10, 10),
],
datetime(2015, 1, 12, 11, 0, 0),
)
== 610
)
assert (
sum_light(
[
datetime(2015, 1, 12, 10, 0, 0),
datetime(2015, 1, 12, 10, 10, 10),
datetime(2015, 1, 12, 11, 0, 0),
datetime(2015, 1, 12, 11, 10, 10),
],
datetime(2015, 1, 12, 11, 0, 10),
)
== 600
)
assert (
sum_light(
[
datetime(2015, 1, 12, 10, 0, 0),
datetime(2015, 1, 12, 10, 10, 10),
datetime(2015, 1, 12, 11, 0, 0),
datetime(2015, 1, 12, 11, 10, 10),
],
datetime(2015, 1, 12, 10, 10, 0),
)
== 620
)
assert (
sum_light(
[
datetime(2015, 1, 12, 10, 0, 0),
datetime(2015, 1, 12, 10, 10, 10),
datetime(2015, 1, 12, 11, 0, 0),
datetime(2015, 1, 12, 11, 10, 10),
datetime(2015, 1, 12, 11, 10, 11),
datetime(2015, 1, 12, 12, 10, 11),
],
datetime(2015, 1, 12, 12, 10, 11),
)
== 0
)
assert (
sum_light(
[
datetime(2015, 1, 12, 10, 0, 0),
datetime(2015, 1, 12, 10, 10, 10),
datetime(2015, 1, 12, 11, 0, 0),
datetime(2015, 1, 12, 11, 10, 10),
datetime(2015, 1, 12, 11, 10, 11),
datetime(2015, 1, 12, 12, 10, 11),
],
datetime(2015, 1, 12, 12, 9, 11),
)
== 60
)
print("The second mission in series is done? Click 'Check' to earn cool rewards!")
Sept. 7, 2022