Last active
June 17, 2016 22:40
-
-
Save juniorbird/3d57f0751d245dd7830e5aaebc6192ec to your computer and use it in GitHub Desktop.
A simple implementation of Merge Ranges in Python, using a for loop
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def free_times(calendar_list): | |
output = [] | |
# This is easier with a list sorted by start time | |
# sort() is mergesort, with O(n) = n log n | |
# which is fast enough to not manually sort. | |
calendar_list.sort(key = lambda event: event[0]) | |
for index in range(len(calendar_list)): | |
if (index > 0): | |
if (calendar_list[index][0] <= calendar_list[index - 1][1]): | |
start = calendar_list[index - 1][0] | |
if (calendar_list[index][1] > calendar_list[index - 1][1]): | |
end = calendar_list[index][1] | |
else: | |
end = calendar_list[index - 1][1] | |
if (len(output) > 0): | |
output[len(output) - 1] = [start, end] | |
else: | |
output.append([start, end]) | |
else: | |
output.append(calendar_list[index]) | |
else: | |
output.append(calendar_list[index]) | |
return output | |
cal = [[3, 4], [9, 12], [1, 3], [6, 8], [9, 10]]; | |
print(free_times(cal)) # [[1, 4], [6, 8], [9, 12]] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment