Real Ultimate Programming

The Home for People Who Like to Flip Out and Write Code

Project Euler: Problem 19

I recently solved Problem 19 from Project Euler. Since I don’t really enjoy date math, I decided to brute force it and use the datetime module from the standard library.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
    from datetime import date


    def next_first_of_month_in_20th():
        """Generator to list every first of the month during the 20th century."""
        first = date(1901, 1, 1)
        yield first
        while first.year < 2001:
            if first.month == 12:
                first = first.replace(year=first.year + 1)
                first = first.replace(month=1)
            else:
                first = first.replace(month=first.month + 1)
            yield first


    def main():
        """
        Solve `Problem 19`_ from Project Euler.
        
        .. _`Problem 19`: http://projecteuler.net/index.php?section=problems&id;=19
        """
        return len([first for first in next_first_of_month_in_20th() if first.weekday() == 6])


    if __name__ == '__main__':
        print main()

Back to flipping out…