project18_count_sundays

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




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值