Python - Algorithm find time slots

后端 未结 1 1077
别跟我提以往
别跟我提以往 2020-12-25 08:32

Let\'s say today I work from 09:00 to 18:00, I have 3 appointments:

  • 10:00 - 10:30
  • 12:00 - 13:00
  • 15:30 - 17:10

I need to find a

相关标签:
1条回答
  • 2020-12-25 09:24
    #time_slots.py
    from datetime import datetime, timedelta
    
    appointments = [(datetime(2012, 5, 22, 10), datetime(2012, 5, 22, 10, 30)),
                    (datetime(2012, 5, 22, 12), datetime(2012, 5, 22, 13)),
                    (datetime(2012, 5, 22, 15, 30), datetime(2012, 5, 22, 17, 10))]
    
    hours = (datetime(2012, 5, 22, 9), datetime(2012, 5, 22, 18))
    
    def get_slots(hours, appointments, duration=timedelta(hours=1)):
        slots = sorted([(hours[0], hours[0])] + appointments + [(hours[1], hours[1])])
        for start, end in ((slots[i][1], slots[i+1][0]) for i in range(len(slots)-1)):
            assert start <= end, "Cannot attend all appointments"
            while start + duration <= end:
                print "{:%H:%M} - {:%H:%M}".format(start, start + duration)
                start += duration
    
    if __name__ == "__main__":
        get_slots(hours, appointments)
    
    
    % python time_slots.py 
    09:00 - 10:00
    10:30 - 11:30
    13:00 - 14:00
    14:00 - 15:00
    
    0 讨论(0)
提交回复
热议问题