pythonalgorithm

Trying to solve problem 19 on Euler Project


The question is:

You are given the following information, but you may prefer to do some research for yourself.

1 Jan 1900 was a Monday. Thirty days has September, April, June and November. All the rest have thirty-one, Saving February alone, Which has twenty-eight, rain or shine. And on leap years, twenty-nine. A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400. How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?

I wrote this code:

if __name__ == '__main__':
    count_sundays = 0
    day_name = 3 # this is tuesday
    day = 1
    month = 1
    year = 1901
    months = {1: 31, 2: 28, 3: 31, 4: 30, 5: 31, 6: 30, 7: 31, 8: 31, 9: 30,
              10: 31, 11: 30, 0: 31}
    
    while not ((year == 2000) and (month == 0) and (day == 0)):
        print(year, month, day)
        if day_name == day == month == 1:
            count_sundays += 1
        day += 1
        day_name += 1
        day_name = day_name % 7
        if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
            months[2] = 29
        else:
            months[2] = 28
        day = day % months[month]

        if day == 1:
            month = month + 1
            month = month % 12

        if month == 1 and day == 1:
            year += 1

    print(count_sundays)

I am getting 14 which is the wrong answer, if anyone can point out what's wrong with my code that would be great.


Solution

  • Your code has issue on following condition, where you are checking if month == 1, which means it'll only count Sundays if it's 1st January of the year.

    if day_name == day == month == 1:
    

    instead you should use:

    if day_name == day == 1:
    

    just a suggestion if you are open to code change, as you are only concern about 1st day of every month, instead of going through every day of the years, traverse through 1st day of every month.
    if __name__ == "__main__":
        count_sundays = 0
        
        week_day = 3  # this is tuesday
        year = 1901
        
        months = {
            1: 31, 2: 28, 3: 31, 4: 30, 5: 31,
            6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31
        }
    
        while year < 2001:
            if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
                months[2] = 29
            else:
                months[2] = 28
            
            for month in range(1, 13):
                # first day of the next month
                week_day = (week_day + months[month]) % 7;
                if week_day == 1: count_sundays += 1
            
            year += 1
    
        print(count_sundays)