我有几个嵌套的for循环,试图找到连续和非连续的工作日将它们打印为字符串。这是一个工作循环示例:
week = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
days1 = ['Mon', 'Tue', 'Wed', 'Fri', 'Sat']
def is_consecutive(d1, d2):
for i in range(0, len(week) - 1):
if d1 == week[i] and d2 == week[i + 1]:
return True
return False
def get_week_string(days):
string = ''
i = 0
next_day = 1
while i < len(days):
if i < len(days) - 1 and is_consecutive(days[i], days[i + 1]):
for j in range(i, len(days) - 1):
if is_consecutive(days[j], days[j + 1]):
next_day = j + 1
else:
break
string = string + days[i] + " - " + days[next_day] + ", "
i = next_day + 1
else:
string = string + days[i] + ", "
i += 1
if string[-2:] == ', ':
string = string[:-2]
return string
print get_week_string(days1)
# prints Mon - Wed, Fri - Sat
我最初试图通过递归来解决这个问题但是失败了。现在我有一个工作的例子,我已经采取了一些更多的刺,但真的可以让我的头围绕它。我让它成功的想法就像:
def recursive_weekdays(days, index):
# Base case
if index == len(days) - 1:
return days[index]
if is_consecutive(days[index], days[index + 1]):
return days[index] + " - " + recursive_weekdays(days, index + 1)
# ... blank here :(
# can't figure out more :/
print recursive_weekdays(days, 0)
任何帮助解决这个问题不仅会让我感到高兴,也会让我今晚睡觉,因为我无法理解它:P
编辑:这是一些测试用例。days1 = ['Mon', 'Tue', 'Wed', 'Fri', 'Sat']
days2 = ['Mon', 'Tue', 'Wed', 'Fri', 'Sat', 'Sun']
days3 = ['Mon', 'Tue', 'Sun']
days4 = ['Wed','Thu', 'Sun']
days5 = ['Wed','Fri', 'Sat']
days1 -> Mon - Wed, Fri - Sat
days2 -> Mon - Wed, Fri - Sun
days3 -> Mon - Tue, Sun
days4 -> Wed - Thu, Sun
days5 -> Wed, Fri - Sat
答案 0 :(得分:3)
我认为这应该适用于所有情况(虽然未经过严格测试)
week = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
days1 = ['Mon', 'Tue', 'Wed', 'Fri', 'Sat']
days2 = ['Mon', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
days3 = ['Mon', 'Wed', 'Thu', 'Sat', 'Sun']
def is_consecutive(d1, d2):
for i in range(0, len(week) - 1):
if d1 == week[i] and d2 == week[i + 1]:
return True
return False
def recursive_weekdays(days, index, in_range=False):
# Base case
if index == len(days) - 1:
return days[index]
if is_consecutive(days[index], days[index + 1]):
if not in_range:
return days[index] + " - " + recursive_weekdays(days, index + 1, True)
else:
return recursive_weekdays(days, index + 1, in_range)
return days[index] + ", " + recursive_weekdays(days, index + 1)
print recursive_weekdays(days1, 0)
print recursive_weekdays(days2, 0)
print recursive_weekdays(days3, 0)
<强>输出强>
Mon - Wed, Fri - Sat
Mon, Wed - Sun
Mon, Wed - Thu, Sat - Sun
这里的诀窍是当你不再在连续几天的范围内时,只返回-
之后的值。
修改强>
以下是测试用例的输出值:
Mon - Wed, Fri - Sat
Mon - Wed, Fri - Sun
Mon - Tue, Sun
Wed - Thu, Sun
Wed, Fri - Sat