19.py 1.67 KB
#!/usr/bin/python

import sys;

MON = 0
TUE = 1
WED = 2
THU = 3
FRI = 4
SAT = 5
SUN = 6

JAN = 1
FEB = 2
MAR = 3
APR = 4
MAY = 5
JUN = 6
JUL = 7
AUG = 8
SEP = 9
OCT = 10
NOV = 11
DEC = 12

MONTHS_31 = [JAN,MAR,MAY,JUL,AUG,OCT,DEC]

class Date:

	def __init__(self,d,m,y):
		self.day = d
		self.month = m
		self.year = y

	def __str__(self):
		return str(self.day) + "/" + str(self.month) + "/" + str(self.year)

def isLeap(year):
	return (year % 4 == 0) and ((year % 100 != 0) or (year % 400 == 0))

def getMonthLimit(month,year):
	limit = 0
	if(month in MONTHS_31):
                limit = 31
        elif(month == FEB):
                if(isLeap(year)):
                        limit = 29
                else:
                        limit = 28
        else:
                limit = 30

	return limit

def SundaysFirstOfMonth(start,end,initial):
	sundays = 0
	currentDay = start.day
	currentMonth = start.month
	currentYear = start.year
	currentWeekday = initial

	limit = getMonthLimit(currentMonth, currentYear)

	while True:
		if(end.day == currentDay and end.month == currentMonth and end.year == currentYear):
			return sundays
		if (currentDay > limit):
			currentMonth += 1
			currentDay = 1
			if currentMonth > 12:
				currentMonth = 1
				currentYear += 1
			limit = getMonthLimit(currentMonth, currentYear)

		if ((currentDay == 1) and (currentWeekday == SUN)):
			sundays += 1

		currentDay += 1
		currentWeekday = (currentWeekday + 1) % 7

strDateEnd = sys.argv[1].split('/')

dateStart = Date(1,1,1901)
dateEnd = Date(int(strDateEnd[0]),int(strDateEnd[1]),int(strDateEnd[2]))

initialDay = TUE
numSundays = SundaysFirstOfMonth(dateStart,dateEnd,initialDay)

print "Result is: " + str(numSundays)