Reputation: 23
I've been thinking hard for a long time but couldn't work this out. Consider the following sequences over time, which records the status of switches:
A = [(10:00, 1), (11:00, 0), (12:00, 1), (12:30, 0),..., (23:00, 1)] # switch A is on at 10:00, off at 11:00 and so on
B = [(10:30, 1), (11:15, 0), (11:30, 1), (12:15, 0),..., (23:30, 0)] # likewise
C = ...
(In reality the time is in the format of python's time.struct_time.)
So basically the structure would be [(time1, status1), (time2, status2)...]. The lists contains data within 24h, and only the switching instances are recorded (so the adjacent "status"es are always opposite to each other). I want to calculate the total amount of time, when all switches A,B,C are on. This seemingly simple question is taking me many days to come up with something useful.
Upvotes: 2
Views: 178
Reputation: 116
How about representing the times a switch is enabled as a list of minutes of the day when a switch is enabled, e.g. A=[600, 601, 602, ..., 659, ..., ]
, where 10am corresponds to minute 600 in the day. Convert the lists to sets and use a sum of the intersections.
Upvotes: 0
Reputation: 117771
First merge all lists into one list of tuples in the format (time, switch, state)
. Then sort all the status switches by time, giving a timeline of events.
Then have three variables, a_on
, b_on
and c_on
. Initialize them as the problem specifies (do they start all off or on, etc). Then do something like this:
last_time = 0 # starting time of data, 0 is here as example
total_time = 0 # 0 seconds
for time, switch, state in state_switches:
if a_on and b_on and c_on:
total_time += time - last_time
if switch == "A":
a_on = state
if switch == "B":
b_on = state
if switch == "C":
c_on = state
last_time = time
Upvotes: 4