Skip to content

Instantly share code, notes, and snippets.

@anilpai
Last active June 26, 2023 12:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anilpai/37f941ab839a9325f65c912640d45765 to your computer and use it in GitHub Desktop.
Save anilpai/37f941ab839a9325f65c912640d45765 to your computer and use it in GitHub Desktop.
Generate Time Series based on trip intervals data
import heapq as hq
def generate_time_series(trips):
trips.sort(key=lambda x: (x[0], x[1]))
series = {}
minStartTime = []
for trip in trips:
if minStartTime and minStartTime[0] <= trip[0]:
# start time of incoming trip is lesser than the earliest end time ( AKA minimum start time)
end = hq.heappop(minStartTime)
series[end] = len(minStartTime)
# push current trip end time to a heap
hq.heappush(minStartTime, trip[1])
series[trip[0]] = len(minStartTime)
# Ending all the active trips
while minStartTime:
end = hq.heappop(minStartTime)
series[end] = len(minStartTime)
# Print the active trips as a time series
sorted_series = dict(sorted(series.items()))
prev_item = None
for item in sorted_series.items():
if prev_item is None:
prev_item = item
else:
print(f"({prev_item[0]},{item[0]}) ====> {prev_item[1]} active trip(s)")
prev_item = item
return ''
trips = [[2, 3], [4, 6], [7, 10], [0, 5]]
print(generate_time_series(trips))
trips2 = [[1, 9], [3, 10], [2, 6], [7, 8]]
print(generate_time_series(trips2))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment