这是我的解决方案:
首先,我创建了一个名为 Day 的新对象,这样我就可以轻松地计算小时和分钟:
from functools import total_ordering
@total_ordering
class Day():
def __init__(self, h=0, m=0):
self.h = (h + m // 60) % 24
self.m = m % 60
def __add__(self, other):
return Day(self.h + other.h, self.m + other.m)
def __iadd__(self, other):
return self.__add__(other)
def __sub__(self, other):
return Day(self.h - other.h, self.m - other.m)
def __isub__(self, other):
return self.__sub__(other)
def __repr__(self):
return f'h: {self.h}, m:{self.m}'
def __str__(self):
return self.__repr__()
def __eq__(self, other):
return self.h == other.h and self.m == other.m
def __gt__(self, other):
return self.h > other.h or (self.h == other.h and self.m > other.m)
def __copy__(self):
return Day(self.h, self.m)
def copy(self):
return self.__copy__()
然后我以Day对象的形式保存了您示例中的数据
start_day = Day(9) # starting working day
end_day = Day(17) # end working day
start_break = Day(12)
end_break = Day(13)
slot_duration = Day(1)
interbreak_duration = Day(0, 15) # break between slots
现在有了这个设置,编写算法来进行计算应该会更容易。
这是我的解决方案的草稿,但效果不佳,我建议您编写一个适合您所需输出的新算法
def calculate(start_day, end_day, start_break, end_break, slot_duration, interbreak_duration):
now = start_day.copy()
break_done = False # mid day break
interbreak_done = True # break between slots
while True:
print(now, end=' ')
if interbreak_done:
print('\tslot', end='')
else:
print('\tbreak', end='')
if break_done:
if interbreak_done:
now += slot_duration
if now == end_day:
print(now)
break
if now >= end_day:
print('\r', end='')
break
interbreak_done = False
else:
now += interbreak_duration
if now == end_day:
print(now)
break
if now > end_day:
print('\r', end='')
break
interbreak_done = True
else:
if interbreak_done:
now += slot_duration
interbreak_done = False
if now == start_break:
print('slot')
if now >= start_break:
print('\r', end='')
now = end_break
interbreak_done = True
break_done = True
continue
else:
now += interbreak_duration
if now >= start_break:
now = end_break
break_done = True
interbreak_done = True
print('\t', now)
输出是:
calculate(start_day, end_day, start_break, end_break, slot_duration, interbreak_duration)
h: 9, m:0 slot h: 10, m:0
h: 10, m:0 break h: 10, m:15
h: 10, m:15 slot h: 11, m:15
h: 11, m:15 break h: 11, m:30
h: 13, m:0 slot h: 14, m:0
h: 14, m:0 break h: 14, m:15
h: 14, m:15 slot h: 15, m:15
h: 15, m:15 break h: 15, m:30
h: 15, m:30 slot h: 16, m:30
h: 16, m:30 break h: 16, m:45
h: 16, m:45 slot
这有点小问题,但它应该可以帮助你开始