算法逻辑计数星期日

2024-05-19 07:04:53 发布

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

我写了一段代码,计算从1901年1月到2000年12月(包括1901年1月到2000年12月)每个星期天在一个月的第一天的次数。我知道正确答案是171,这比我得到的多了一个。这意味着要么我的算法逻辑有错误,要么我误解了问题陈述。我希望有人指出我的错误。这是问题陈述和我的代码:

1 Jan 1900 was a Monday. Thirty days has September, April, June and November. All the rest have thirty-one, Saving February alone, Which has twenty-eight, rain or shine. And on leap years, twenty-nine.

A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.

How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?

monthdict = {
    1: 31,
    2: 28,
    3: 31, 
    4: 30,
    5: 31,
    6: 30,
    7: 31,
    8: 31,
    9: 30,
    10: 31,
    11: 30,
    12: 31
}

ly_monthdict = {
    1: 31,
    2: 29,
    3: 31, 
    4: 30,
    5: 31,
    6: 30,
    7: 31,
    8: 31,
    9: 30,
    10: 31,
    11: 30,
    12: 31
}

leap_year = False
sundays = 0
first_sunday = 6

for year in range(1901, 2001):
    if year % 4 == 0 and year % 100 != 0:
        leap_year = True
    elif year % 100 == 0 and year % 400 == 0:
        leap_year = True
    else:
        leap_year = False

    if leap_year:
        for month in range(1, 13):
            if first_sunday == 1:
                sundays += 1

            curr_sunday = first_sunday
            while curr_sunday < ly_monthdict[month]:
                curr_sunday += 7

            first_sunday = curr_sunday - ly_monthdict[month]


    else:
        for month in range(1, 13):
            curr_sunday = first_sunday
            while curr_sunday < monthdict[month]:
                curr_sunday += 7

            first_sunday = curr_sunday - monthdict[month]
            if first_sunday == 1:
                sundays += 1

print(sundays, "Sundays occured on the first of the month")

Tags: andtheinforifonlyyear
1条回答
网友
1楼 · 发布于 2024-05-19 07:04:53

看起来很傻,但您的两个内部for..in块并不相同

如果您将if first_sunday == 1检查移动到非闰年循环的开始处,您将得到171作为您的答案

if leap_year:
    for month in range(1, 13):
        if first_sunday == 1:
            sundays += 1
        curr_sunday = first_sunday
        while curr_sunday < ly_monthdict[month]:
            curr_sunday += 7
        first_sunday = curr_sunday - ly_monthdict[month]
else:
    for month in range(1, 13):
        if first_sunday == 1:     #Moved this block up
            sundays += 1
        curr_sunday = first_sunday
        while curr_sunday < monthdict[month]:
            curr_sunday += 7
        first_sunday = curr_sunday - monthdict[month]

同样值得庆幸的是,我已经十多年没有遇到过这些问题了。我建议您合并这两个循环,并切换使用的dict引用,而不是复制代码

相关问题 更多 >

    热门问题