Project Euler #19 asks:
How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
I'm hoping I wasn't too off course from the spirit of the exercise by making use of my favorite libraries: pandas
.
import pandas as pd
rng = pd.date_range(start='1/1/1901', end='12/31/2000', freq='D')
count = 0
for date in rng:
if date.day == 1 and date.weekday() == 6:
count += 1
count
It's a rather simple problem and a rather simple solution. I just made use of the date_range
function that pandas has builtin that works well with datetime
objects in python.
While I don't think my usual questions apply. Some specific questions:
Is it pythonic to run the for loop as such, or would a list comprehension surrounded by a len be more pythonic, e.g.
len([x for x in rng if date.day == 1 and date.weekday() == 6])
? Or is something entirely else even more pythonic?Is there a way to avoid iterating over an object as large as
rng
is with it's 30,000+ items to avoid memory usage? If so what would be a preferred method (just pseudo-code or however you prefer to explain.)As my attention has been brought to how powerful
itertools
is when improving performance and substituting lists for generators, I'm wondering how I would improve upon the below code withitertools
if there is any such a way.
I'm hoping I wasn't too off course from the spirit of the exercise by making use of my favorite libraries
The spirit of Project Euler is to learn. You know have learned how to do it. Next step is to learn whether this is the most Pythonic way to do it. You did not go against any spirit. \$\endgroup\$ – Mast Sep 30 '15 at 17:54freq
such that rng only contains sundays or first of months. (see stackoverflow.com/questions/13445174/date-ranges-in-pandas ) \$\endgroup\$ – bdecaf Oct 1 '15 at 6:27