The following scripts calculate a list with the number of people occupied at each time interval.
The intervals are defined by the timestamps of two consecutive events that come from the sorted list events_timeline
.
Also, start_ts
and end_ts
are taking into account for intervals calculation and for each event, one person is occupied.
input data to be used in the following scripts:
MINIMUM_EVENT_INTERVAL = 1
start_ts = 1598939760.0
end_ts = 1598939792.0
events_timeline = [(1598939761.0, 's'), (1598939771.0, 's'), (1598939781.0, 'e'),
(1598939791.0, 'e')] # 's' and 'e' denote start and end event respectively
1st approach:
people_occupied = []
start_events = 0
end_events = 0
num_events_timeline = len(events_timeline)
if events_timeline[0][0] - start_ts >= MINIMUM_EVENT_INTERVAL:
people_occupied.append(0)
for index, (ts, event) in enumerate(events_timeline):
if event == 's':
start_events += 1
else:
end_events += 1
if index != num_events_timeline - 1 and ts == events_timeline[index + 1][0]:
continue
if index == num_events_timeline - 1 and end_ts - ts < MINIMUM_EVENT_INTERVAL:
break
people_occupied.append(start_events - end_events)
print(f'1st approach: {people_occupied}')
2nd approach:
currently_occupied = 0
people_occupied = []
if events_timeline[0][0] - start_ts >= MINIMUM_EVENT_INTERVAL:
people_occupied.append(0)
for (start_time, event_type), (end_time, _) in zip(events_timeline[:-1], events_timeline[1:]):
if event_type == 's':
currently_occupied += 1
else:
currently_occupied -= 1
if end_time > start_time:
people_occupied.append(currently_occupied)
if end_ts - events_timeline[-1][0] >= MINIMUM_EVENT_INTERVAL:
people_occupied.append(0)
print(f'2nd approach: {people_occupied}')
Both approaches do the job, but which one of them should be preferred and why?