2
我有几个嵌套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
你能否提供几个测试案例和预期输出为每个? – tijko
当然,添加为编辑 – span