Created
September 27, 2016 22:39
-
-
Save nguyent/115b5ed2964e3a56a8ab011448fe707f to your computer and use it in GitHub Desktop.
given a list of dates, create a list of lists containing contiguous ranges Raw
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 datetime import timedelta | |
| from datetime import datetime | |
| def toDate(s): | |
| return datetime.strptime(s, '%Y-%m-%d') | |
| def consecutive(d1, d2): | |
| return toDate(d1) + timedelta(days=1) == toDate(d2) | |
| def findRangesRecursive(dates, acc=[], candidate=[]): | |
| if not dates: | |
| return acc + [candidate] | |
| else: | |
| current_day = dates[0] | |
| if consecutive(candidate[-1], current_day): | |
| candidate.append(current_day) | |
| else: | |
| acc.append(candidate) | |
| candidate = [current_day] | |
| return findRangesRecursive(dates[1:], acc, candidate) | |
| def findRanges(dates): | |
| return findRangesRecursive(dates[1:], acc=[], candidate=dates[0:1]) | |
| # we could be stricter and require dates be a list of datetime objects |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment