19.py 2.41 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 calcNumDays(start,end):
	days = 0
	currentMonth = start.month
	currentDay = start.day
	for year in range(start.year+1,end.year):
		if(isLeap(year)):
			days += 366
		else:
			days += 365

	leap = 0
	# Beginning
	year = start.year
	if(isLeap(year)):
		leap = 1

	for month in range(start.month+1, DEC+1):
		if(month in MONTHS_31):
			days += 31
		elif(month == FEB):
			days += 28
		else:
			days += 30
		
	days += (31 - start.day + 1 + leap)

	leap = 0
	# End
	year = end.year
	if(isLeap(year)):
		leap = 1

	for month in range(JAN,end.month):
		if(month in MONTHS_31):
                        days += 31
                elif(month == FEB):
                        days += 28
                else:
                        days += 30

	days += (end.day + leap)

	return days

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,initial,numDays):
	sundays = 0
	currentDay = start.day
	currentMonth = start.month
	currentYear = start.year
	currentWeekday = initial

	limit = getMonthLimit(currentMonth, currentYear)

	for i in range(0,numDays):
		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

	return sundays

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

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

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

print "Result is: " + str(numSundays)