Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # @hieuza [at] gmail.com
- # 04.Jan.2014
- # the months with 13th Friday of a year
- import datetime
- months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
- days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
- days_leap = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
- # start_day: the weekday of 1st January.
- # 0: Monday,... 6: Sunday
- def friday13_month(days, start_day):
- accum = [13]
- for x in days[:-1]:
- accum.append(accum[-1] + x)
- # weekday of day 13, if 01/Jan is on Monday (0)
- # must minus 1, because day started at 1
- day13_start0 = [(x - 1) % 7 for x in accum]
- # day 13, in considerate of the start day
- day13 = [(x + start_day) % 7 for x in day13_start0]
- # which month has Friday 13
- res = []
- for i, x in enumerate(day13):
- if x == 4: # Friday
- res.append(i)
- return res
- def is_leap_year(year):
- return year % 400 == 0 or (year % 100 != 0 and year % 4 == 0)
- def which_month_friday13(year):
- day1 = datetime.date(year, 1, 1)
- start_day = day1.weekday()
- # print 'year:', year, 'start_day:', start_day
- if is_leap_year(year):
- res = friday13_month(days_leap, start_day)
- else:
- res = friday13_month(days, start_day)
- print [months[i] for i in res]
- return res
- def test_is_leap_year():
- print '2000:', is_leap_year(2000)
- print '1800:', is_leap_year(1800)
- print '2008:', is_leap_year(2008)
- def test_friday13(year):
- # year = 2014
- res = which_month_friday13(year)
- # check the correct Friday 13
- for m in res:
- d = datetime.date(year, m + 1, 13)
- if d.weekday() != 4:
- print 'ERROR: 13/%s is not Friday' % months[m]
- # check that there's no other Friday 13
- for m in xrange(12):
- if m in res: continue
- d = datetime.date(year, m + 1, 13)
- if d.weekday() == 4:
- print 'ERROR: 13th %s is Friday' % months[m]
- def test_interactive():
- print 'Enter a year to print the month with Friday 13. 0 to exit'
- while True:
- year = int(raw_input('year: '))
- if year == 0:
- break
- test_friday13(year)
- if __name__ == '__main__':
- # test_is_leap_year()
- # test_friday13(2014)
- test_interactive()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement