我正在研究项目欧拉问题19的解决方案
https://projecteuler.net/problem=19
目标是找到20世纪第一个月的星期日数量。我试图仅使用循环(不使用日期时间)来完成问题。
这是我现在的代码:
days = []
yearCnt = 1900;
dayCnt = 1;
Jan = 31;
Mar = 31;
Apr = 30;
May = 31;
Jun = 30;
Jul = 31;
Aug = 31;
Sep = 30;
Oct = 31;
Nov = 30;
Dec = 31;
while yearCnt < 2001:
if yearCnt == 1900:
Feb = 28;
elif yearCnt%4 == 0:
Feb = 29;
else:
Feb = 28;
days.append(1);
while dayCnt < Jan:
days.append(0);
dayCnt += 1;
dayCnt = 1;
days.append(1);
while dayCnt < Feb:
days.append(0);
dayCnt += 1;
dayCnt = 1;
days.append(1);
while dayCnt < Mar:
days.append(0);
dayCnt += 1;
dayCnt = 1;
days.append(1);
while dayCnt < Apr:
days.append(0);
dayCnt += 1;
dayCnt = 1;
days.append(1);
while dayCnt < May:
days.append(0);
dayCnt += 1;
dayCnt = 1;
days.append(1);
while dayCnt < Jun:
days.append(0);
dayCnt += 1;
dayCnt = 1;
days.append(1);
while dayCnt < Jul:
days.append(0);
dayCnt += 1;
dayCnt = 1;
days.append(1);
while dayCnt < Aug:
days.append(0);
dayCnt += 1;
dayCnt = 1;
days.append(1);
while dayCnt < Sep:
days.append(0);
dayCnt += 1;
dayCnt = 1;
days.append(1);
while dayCnt < Oct:
days.append(0);
dayCnt += 1;
dayCnt = 1;
days.append(1);
while dayCnt < Nov:
days.append(0);
dayCnt += 1;
dayCnt = 1;
days.append(1);
while dayCnt < Dec:
days.append(0);
dayCnt += 1;
dayCnt = 1;
yearCnt += 1;
sunCnt = 6;
while sunCnt <= len(days):
days[sunCnt] += 1;
sunCnt += 7;
print(days.count(2));
我们的想法是创建一个包含所有日期的数组,其中第一个月的位置标记为1。然后另一个while循环遍历该数组并添加1以标记所有星期日。从理论上讲,2的数量应该标志着月初的星期日数量。
它目前给出答案173.我知道答案是171但我想知道我哪里出错了。
答案 0 :(得分:0)
如果您将代码更改为在1901年1月1日开始计数,则它可以工作。您只需要在标记每个星期日的末尾更改循环。
sunCnt = 6;
# Skip the year 1900
# Adding 364 will get to 1901 without messing up the day of the week
sunCnt += 364;
while sunCnt <= len(days):
days[sunCnt] += 1;
sunCnt += 7;