princeofsudan

Project Euler#19 Counting Sundays

Mar 17th, 2013
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.62 KB | None | 0 0
  1. #You are given the following information, but you may prefer to do some research for yourself.
  2.  
  3. #    *1 Jan 1900 was a Monday.
  4. #    *Thirty days has September,
  5. #    April, June and November.
  6. #    All the rest have thirty-one,
  7. #    Saving February alone,
  8. #    Which has twenty-eight, rain or shine.
  9. #    And on leap years, twenty-nine.
  10. #    *A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.
  11.  
  12. #How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
  13.  
  14. def isLeap(year):
  15.     """Return True for leap years, False for non-leap years."""
  16.     return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
  17.  
  18. def add2Cal(days):
  19.     day = 1
  20.     weekDay = calender[-1][3]
  21.     weekDayIndex = weekDays.index(weekDay)
  22.     while day <= days:
  23.         calender.append([day,month,year,weekDays[((weekDayIndex+1)%7)]])
  24.         day += 1
  25.         weekDayIndex = ((weekDayIndex+1)%7)
  26.  
  27.  
  28.  
  29. years = range(1900,2001)
  30. months = ['Jan','Feb','March','April','May','June',\
  31.           'July','August','Sept','Oct','Nov','Dec']
  32. weekDays = ['Mon','Tue','Wed','Thr','Fri','Sat','Sun']
  33. calender = [[0,0,0,'Sun']]
  34.  
  35. for year in years:
  36.     for month in months:
  37.    
  38.         if month in ['Sept','April','June','Nov']:
  39.             add2Cal(30)
  40.        
  41.         elif month == 'Feb' and isLeap(year):
  42.             add2Cal(29)
  43.  
  44.         elif month == 'Feb':
  45.             add2Cal(28)
  46.  
  47.         else:
  48.             add2Cal(31)
  49. count = 0
  50.  
  51. for days in calender:
  52.  
  53.     if days[2] > 1900 and days[0] == 1 and days[3] == 'Sun':
  54.         count += 1
  55.  
  56. print count
Advertisement
Add Comment
Please, Sign In to add comment