Last active
June 17, 2016 22:47
-
-
Save juniorbird/a4a987ee141737324fae46ca08912da1 to your computer and use it in GitHub Desktop.
A simple implementation of Merge Ranges in Python, using reduce
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
from functools import reduce | |
def merge_arrays(accumulator, new): | |
# Since Python doesn't have multiline lambdas | |
# we define our reducer function here | |
last = len(accumulator) - 1 | |
if (new[0] <= accumulator[last][1]): | |
start = accumulator[last][0] | |
end = new[1] if (new[1] > accumulator[last][1]) else accumulator[last][1] | |
accumulator[last] = [start, end] | |
else: | |
accumulator.append(new) | |
return accumulator | |
def free_times(calendar_list): | |
# This is easier with a list sorted by start time | |
# sorted() is mergesort, with O(n) = n log n | |
# which is fast enough to not manually sort. | |
return reduce( | |
merge_arrays, | |
sorted(calendar_list, key = lambda event: event[0]), | |
[calendar_list[0]] | |
) | |
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