patternpythonMinor
Project Euler #19: Counting Sundays in the 20th century using Pandas
Viewed 0 times
sundaysthecountingpandas20thprojecteulerusingcentury
Problem
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:
It's a rather simple problem and a rather simple solution. I just made use of the
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.
-
Is there a way to avoid iterating over an object as large as
-
As my attention has been brought to how powerful
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
countIt'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 with itertools if there is any such a way.Solution
It is good to use a library rather than re-inventing everything yourself. Just be sure to avoid explicit looping in Python:
The above sums the number of times that
sum(date.day == 1 and date.weekday() == 6 for date in rng)The above sums the number of times that
date.day == 1 and date.weekday() == 6 automatically, with no loops of counters, It should also be more efficient (sum is implemented in C)Code Snippets
sum(date.day == 1 and date.weekday() == 6 for date in rng)Context
StackExchange Code Review Q#106161, answer score: 5
Revisions (0)
No revisions yet.