gpt4 book ai didi

python - 将 for 循环转换为递归 [查找连续的工作日]

转载 作者:太空宇宙 更新时间:2023-11-04 01:22:30 25 4
gpt4 key购买 nike

我有几个嵌套的 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

最佳答案

我认为这应该适用于所有情况(尽管没有经过严格测试)

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

关于python - 将 for 循环转换为递归 [查找连续的工作日],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20252939/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com