Project Euler 19: Counting Sundays

Counting Sundays

First Sundays

Modern Gregorian Calendar

Warning: Please only read this post, when you are absolutely sure, that you don’t want to take part in the challenge that is Project Euler. My posts will spoil the solution for you. I’m posting my solutions to show one possible way on how to solve the problems in case you want to compare your solutions with mine or are stuck and gave up on solving the problem.

Problem 19 has you count the number of Sundays, that fell on the first day of a month in the whole twentieth century. This problem can be solved rather easy, when using libraries that support date objects.

Solving this problem the complicated way by checking counting up the total days in the century in an integer and manually figuring out, if the given Sunday is a also the first day of a month can take a lot of effort, because there are so many exceptions you would have to pay attention to (number of days in a month, leap years,…).

Date

Python offers a datetime module that already contains a date object, that can represent a date in the Gregorian calendar format. The module also has a weekday() function, that returns the weekday that falls on that date and that is everything we need to solve this problem.

Code

My program starts at January 1st 1901 and from there on checks every first day of each month until December 31st 2000. The function weekday() returns a zero if the date given is a Sunday, so that’s when we increment our solution counter.

Here’s the code:

"""How many Sundays fell on the first of the month 
during the twentieth century (1 Jan 1901 to 31 Dec 2000)?"""

from datetime import *

counter = 0
year = 1901
month = 1

curr_day = date(year,month,1)

while(curr_day.year < 2001):
	if(curr_day.weekday() == 6):
		counter += 1
	if(month+1 == 13):
		month = 1
		year += 1
	else:
		month += 1
	curr_day = date(year,month,1)

print("Counter: " + str(counter))

The program needs 0.0149 seconds of processing time to calculate the solution.

This problem was really easy and short, but it showed that it is often smarter and faster to use preexisting libraries, instead reinventing the wheel by creating your own date class.

Hope it was a fun read, don’t be hesitant to send me suggestions on improving the algorithms via email at ratherreadblog@gmail.com or by leaving a comment at the post. You can also subscribe to my mailing list here if you always want to stay up-to-date with my newest posts and changes on the website.

 

 

The post Project Euler 19: Counting Sundays appeared first on Rather Read.