checkio-unlucky days

Friday 13th or Black Friday is considered as unlucky day. Calculate how many unlucky days are in the given year.
Find the number of Friday 13th in the given year.
Input: Year as an integer.
Output: Number of Black Fridays in the a year as an integer.
Precondition: 1000 < |year| < 3000

大意:给定一个年份,判断此年份中13号星期五的次数。即某月的13号同时也是周五的次数。想法很简单12个月份遍历,判断是否为周五。import datetime模块计算某个日期是周几。

import datetime
#sum=0
def checkio(year):
    sum=0
    for i in range(1,13):
        anyday=datetime.datetime(year,i,13).strftime("%w")
        if anyday == '5':
            sum+=1
    return sum

if __name__ == '__main__':
    #These "asserts" using only for self-checking and not necessary for auto-testing
    assert checkio(2015) == 3, "First - 2015"
    assert checkio(1986) == 1, "Second - 1986"

其他方法大同小异。贴一个简便的:by

from datetime import date
​
def checkio(year):
    return sum(date(year, month, 13).weekday() == 4 for month in range(1, 13))

这种发放简便。
贴一个例子:

def dj(x):
    return sum(x>=i for i in range(10))
print(dj(0))

输出结果是1。

你可能感兴趣的:(checkio-unlucky days)