Skip to content

Instantly share code, notes, and snippets.

@juniorbird
Last active June 17, 2016 22:47
Show Gist options
  • Save juniorbird/a4a987ee141737324fae46ca08912da1 to your computer and use it in GitHub Desktop.
Save juniorbird/a4a987ee141737324fae46ca08912da1 to your computer and use it in GitHub Desktop.
A simple implementation of Merge Ranges in Python, using reduce
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