Skip to content

Instantly share code, notes, and snippets.

@aerosol
Created January 3, 2011 21:33
Show Gist options
  • Save aerosol/764007 to your computer and use it in GitHub Desktop.
Save aerosol/764007 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# -*- coding: utf-8 *-*
import datetime
import itertools
class WeeklySchedule(object):
def __init__(self, timeline=None):
if timeline is None:
timeline = dict([(w,0) for w in range(7*24)])
self.timeline = timeline
def book_term(self, start, end):
self.mark_mode = False
i_start = (start.weekday()+1) * start.hour
i_end = (end.weekday()+1) * end.hour
assert i_start in self.timeline
assert i_end in self.timeline
cycle = itertools.cycle(self.timeline)
for moment in cycle:
if int(moment) == int(i_start):
self.mark_mode = True
if self.mark_mode:
assert self.timeline[moment] == 0
self.timeline[moment]=1
if self.mark_mode and int(moment) == int(i_end):
return self.timeline
def is_term_available(self, term):
i = (term.weekday()+1) * term.hour
return self.timeline[i] == 0
if __name__ == '__main__':
term1 = datetime.datetime.now()
term2 = term1 + datetime.timedelta(days=1)
print 'I am going to book term from %s to %s' % (term1, term2)
print '-'*40
schedule = WeeklySchedule()
print 'Check if today is available: %s.' % \
schedule.is_term_available(term1)
print '... booking'
timeline = schedule.book_term(term1, term2)
#print [k for k,v in timeline.items() if v==1]
print 'Check if today is available: %s.' % \
schedule.is_term_available(term1)
print 'I will try to do it again, backwards this time!'
print 'This should fail!'
print '-'*40
try:
schedule.book_term(term2, term1)
print 'Something went wrong, this code sucks :('
except AssertionError, e:
print 'Booking failed. Everything works as expected.'
print '-'*40
print 'Trying backwards (inverse) on a clean timeline.'
schedule = WeeklySchedule()
print 'Check if today is available: %s.' % \
schedule.is_term_available(term1)
print '... booking'
timeline = schedule.book_term(term2, term1)
print '-'*40
print 'Check if today is available: %s.' % \
schedule.is_term_available(term1)
#print [k for k,v in timeline.items() if v==1]
print 'Done.'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment