You are given the following information, but you may prefer to do some research for yourself.
- 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)?
我的代码:
#encoding=utf-8
import operator
def isleapyear(intyear):
#判断某年是不是闰年
success=False
if intyear%100==0:
if not intyear%400:
success=True
else:
if not intyear%4:
success=True
return success
year_days_pairs=dict([(year,366) if isleapyear(year) else (year,365) for year in xrange(1900,2001)])#求出每年的天数
weekday,count=0,0#星期几(0,表示星期天)
matchedlist=[]#存储一月中的星期天
for year in xrange(1900,2001):
for day in xrange(year_days_pairs[year]):
templist=(year,day,weekday)
if day in range(0,31) and not weekday:
matchedlist.append(templist)
weekday=(weekday+1)%7
#totaldays=reduce(operator.add,dayslist)
matchedlist=filter(lambda x:x[0]>=1901,matchedlist)
print len(matchedlist)
输出的结果为
442
但是通不过。真奇怪!!!!
原来是我理解错了。我理解成了。落在第一个月的星期天有多少个。而原题是落在每个月的每一天有多少个
#encoding=utf-8
import operator
import json
def isleapyear(intyear):
#判断某年是不是闰年
success=False
if intyear%100==0:
if not intyear%400:
success=True
else:
if not intyear%4:
success=True
return success
year_days_pairs=dict([(year,366) if isleapyear(year) else (year,365) for year in xrange(1900,2001)])#求出每年的天数
weekday,count=0,0#星期几(0,表示星期天)
matchedlist=[]#存储一月中的星期天
tempdays=[0]*12
for month in xrange(0,12):
if month in (6,8,11):
tempdays[month]=30
elif month==2:
tempdays[month]=28
else:
tempdays[month]=31
tempdaysstr=json.dumps(tempdays)
total_list=dict()
for year in xrange(1901,2001):
actualdays=json.loads(tempdaysstr)
if isleapyear(year):#闰年
actualdays[1]=29
for month in xrange(0,12):
total_days=0#计算从1900年1月1日到当前日期的天数
for tempyear in xrange(1900,year):
total_days+=year_days_pairs[tempyear]
for tempmonth in xrange(0,month):
total_days+=actualdays[tempmonth]
if not total_days%7:
matchedlist.append((year,month,0,'monday'))
#totaldays=reduce(operator.add,dayslist)
matchedlist=filter(lambda x:x[0]>=1901,matchedlist)
print len(matchedlist)
结果为
171