约会过程中的无限循环

2024-10-02 10:32:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我在这里找到了一个有同样问题的人: Python daysBetweenDate

然而,他们的代码和我的不同,我的代码似乎解决了在那篇文章的答案中指出的问题。你知道吗

在我的代码中,我不明白为什么我会运行到一个无限循环中。你知道吗

def leap_year_check(year):
    if (year%4==0 and year%100==0 and year%400==0) or (year%4==0 and year%100!=0):
        return True
    else:
        return False
    #TESTED-leap_year_check-PASSED

def nextDay(year, month, day):
    if month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12 and day < 31:
        return year, month, day + 1
    if month == 4 or month == 6 or month == 9 or month == 11 and day < 30:
        return year, month, day + 1
    if month == 2 and day <28:
        return year, month, day + 1
    if month == 2 and leap_year_check(year)==True and day==28:
        return year, month, day + 1
    else:
        if month == 12:
            return year + 1, 1, 1
        else:
            return year, month + 1, 1
    #TESTED nextDay - PASSED

def dateIsBefore(year1, month1, day1, year2, month2, day2):
    if year1 < year2:
        return True
    if year1 == year2:
        if month1 < month2:
            return True
        if month1 == month2:
            return day1 < day2
    return False        
    #TESTED dateIsBefore - PASSED

def daysBetweenDates(year1, month1, day1, year2, month2, day2):
    assert not dateIsBefore(year2, month2, day2, year1, month1, day1)
    days = 0
    while dateIsBefore(year1, month1, day1, year2, month2, day2):
        year1, month1, day1 = nextDay(year1, month1, day1)
        days += 1
    return days
    #***Keep running into infinite loop when testing daysBetweenDates
    #ALL other functions operate correctly when tested on their own
    #ALL other functions work together EXCEPT when running daysBetweenDates

def test():
    test_cases = [((2012,1,1,2012,2,28), 58), 
                  ((2012,1,1,2012,3,1), 60),
                  ((2011,6,30,2012,6,30), 366),
                  ((2011,1,1,2012,8,8), 585 ),
                  ((1900,1,1,1999,12,31), 36523)]

    for (args, answer) in test_cases:
        result = daysBetweenDates(*args)
        if result != answer:
            print "Test with data:", args, "failed"
        else:
            print "Test case passed!"

test()

据我所知,daysbetweedates正在运行nextDay函数并将+1增加到days,只要dateIsBefore返回False,那么当dateIsBefore变为True时,这两个值加起来应该等于这两个值之间的天数。你知道吗

很明显我遗漏了什么。你知道吗

我明白,我正在进行的方式可能是难以置信的效率低下,但它是为了学习的目的,我肯定还没有在这一点上,我需要把重点放在优化。现在我只是想了解如何使代码工作。你知道吗

任何帮助都将不胜感激。你知道吗


Tags: orandtruereturnifdefyearday
1条回答
网友
1楼 · 发布于 2024-10-02 10:32:33

学习代码的一部分就是学习调试。试着把一个print语句显示year1,month1,day1的当前值放在daysbetweeddates的while循环中,你就会看到发生了什么:nextDay只是不断地增加一天,而不是增加月份或年份。你知道吗

相关问题 更多 >

    热门问题