首页 > 解决方案 > 递归函数在Python中不返回值

问题描述

我正在开发一个预算应用 API,它允许用户输入他们的支付日期 [1, 15] 等。它将采用列表格式,然后让他们有一个“最后支付日期”例如 2020 年 5 月 17 日。我想返回具有开始日期属性和结束日期属性的 PayPeriodModel 对象列表。因此,last_paid 的示例是:datetime = 05/17/2020,pay_dates = [1,15]。应该有一个 PayPeriodModel 对象列表返回:
6/01/2020 - 6/14/2020 6/15/2020 - 6/30/2020 ...等

这是我到目前为止的代码,我不确定它为什么不起作用。如果有人有任何想法甚至不同的方法来解决这个问题,请告诉我!

from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
import json

from models.user import UserModel

class PayPeriodModel():
    def __init__(self, start: datetime, end: datetime):
        self.start = start
        self.end = end

    def __str__(self):
        return f"{self.start} - {self.end}"
        #return f"Pay period starting {datetime.strftime(self.start, '%m/%d/%Y')} and ending {datetime.strftime(self.end, '%m/%d/%Y')}"

    def start_day(self):
        return datetime.strptime(self.start, '%d')

    def end_day(self):
        return datetime.strptime(self.end, '%d')

    @classmethod
    def get_pay_periods(self, user: UserModel, count):
        pay_periods = []

        def find_pay_periods_with_pay_dates(start_date: datetime, dates: list, count: int):
            # Take month and year of start_date for testing against the list of dates
            m = start_date.month
            y = start_date.year
            # if we have to add to a month and its 13, then we need to add a year
            new_month = False

            # Test against the dates of the pay_dates list to see if either one is next
            for date in dates:
                test_date = datetime(y, m, date)
                if test_date > start_date:
                    if count == 0:
                        return test_date - timedelta(days=1)
                    pp = PayPeriodModel(test_date, find_pay_periods_with_pay_dates(test_date, dates, count-1))
                    pay_periods.append(pp)
                # If we exhausted our list, then we must need a new month
                elif date == dates[-1]:
                    new_month = True

            if new_month == True:
                new_month = m+1
                new_year = y+1 if new_month == 13 else 0
                new_month = 1 if new_month == 13 else new_month
                test_date = datetime(y, m, dates[0]) + relativedelta(month=new_month, year=new_year)
                if count == 0:
                    return test_date - timedelta(days=1)
                pp = PayPeriodModel(test_date, find_pay_periods_with_pay_dates(test_date, dates, count-1))
                pay_periods.append(pp)

        find_pay_periods_with_pay_dates(user.last_pay_date, json.loads(user.pay_dates), count)

        return pay_periods

这一直给我:

2020-07-15 00:00:00 - 2020-7-31
2020-07-01 00:00:00 - None
2020-06-15 00:00:00 - None
2020-06-01 00:00:00 - None

标签: pythonrecursion

解决方案


推荐阅读