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:
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
rngis 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
itertoolsis when improving performance and substituting lists for generators, I'm wondering how I would improve upon the below code with
itertoolsif there is any such a way.