days日计算器代码错误,请指出我要去哪里

时间:2019-04-23 04:04:53

标签: python-3.x

在练习Python时,我在Daily编程subreddit中发现了这个问题,这是链接https://www.reddit.com/r/dailyprogrammer/comments/b0nuoh/20190313_challenge_376_intermediate_the_revised/,我似乎无法使我的代码正常工作,请帮助我...

    def leaps(year_1, year_2):
        number_of_leaps = 0
        if year_1 == year_2:
            return number_of_leaps
        if year_1 % 4 != 0:
            year_1 += 4 - (year_1 % 4)
        if year_1 % 100 == 0:
            if year_1 % 900 == 200 or year_1 % 900 == 600:
                start_year = year_1
            else:
                start_year = year_1 + 4
        else:
            start_year = year_1
        if start_year >= year_2:
            return number_of_leaps
        else:
            for year in range(start_year, year_2, 4):
                if year % 100 == 0:
                    if year % 900 == 200 or year_1 % 900 == 600:
                        number_of_leaps += 1
                else:
                    number_of_leaps += 1
            return number_of_leaps


    print(leaps(1234, 5678))
    print(leaps(123456, 7891011))

实际输出应该分别为10771881475,但我似乎得到了10721872844,请告诉我问题所在。

1 个答案:

答案 0 :(得分:1)

根据reddit链接,它是一个revised Julian日历,因此逻辑将如下所示

def check_leap(year):
    #A leap year is divisible by 4 but not by 100
    if year % 4 == 0 and year % 100 != 0:
        return True
    # A leap year leaves 200 or 600 reminder when divided by 900
    if year % 900 == 200 or year % 900 == 600:
        return True
    #All other cases are non leap years
    return False

def leaps(year_1, year_2):
    number_of_leaps = 0
    #If year_1 is bigger than year_2, range is incorrect
    if year_1 > year_2:
        return number_of_leaps

    for year in range(year_1, year_2):
        if(check_leap(year)):
            number_of_leaps+=1

    return number_of_leaps

检查输出,我们得到。

leaps(2016, 2017)
leaps(2019, 2020)
leaps(1900, 1901)
leaps(2000, 2001)
leaps(2800, 2801)
leaps(123456, 123456)
leaps(1234, 5678)
leaps(123456, 7891011)
1
0
0
1
0
0
1077
1881475