hi
i recently found an interesting problem(#19) on the project euler website - projecteuler.net
The real answer is 171 and i am getting 175
What is wrong with this code-

``````def sunday():

c=0
sun=0
months=[31,59,90,120,151,181,212,243,273,304,334,365]
leapmonths=[31,60,91,121,152,182,213,244,274,305,335,366]

for i in range(1901,2001):
n=leap(i)                    #Checking if year is leap year
if n == True:               # if it is...
c=0                     #set c and m to 0
for j in range(1,366):  #Till a leap year...
c+=1                #c is the count of days
for k in leapmonths:#if a month starts
if k == j:
if c%6 == 0:# if day is sunday
sun+=1      #increment count of sundays

elif n == False:            # if it is not a leap year
c=0
for j in range(1,365):
c+=1
for k in months:
if k == j:
if c%6 == 0:
sun+=1
return sun        #Return the number of sundays

def leap(x):
if x%4 == 0 and (x%100 != 0 or x%400 == 0):
return True
else:
return False
``````

Any help will be appriciated!
Thanks!

One problem is that you start each year with c = 1 on the first day. Since your criterion for sundays is `c%6 == 0`. It means that every year starts with a tuesday.

Date and time measurement is a complex area full of tricky problems and unexpected edge-cases.
This is why we have and should use libraries for this.
It can of course be fun to do this manually,but also painful if you try for a long periods of time like this.

Just …

## All 4 Replies

One problem is that you start each year with c = 1 on the first day. Since your criterion for sundays is `c%6 == 0`. It means that every year starts with a tuesday.

Date and time measurement is a complex area full of tricky problems and unexpected edge-cases.
This is why we have and should use libraries for this.
It can of course be fun to do this manually,but also painful if you try for a long periods of time like this.

Just a demo how it can look with datetime module.

``````import datetime

date = datetime.date(1901, 1, 1)
days = 0
while date.year < 2001:
if date.weekday() == 6 and date.day == 1:
days += 1
date += datetime.timedelta(days=1)

print 'Sundays that felled on the first month during the twentieth century was {}'.format(days)

"""Output-->
Sundays that felled on the first month during the twentieth century was 171
"""
``````