Home > OS >  Python - Basic Leap year function problem (Novice)
Python - Basic Leap year function problem (Novice)

Time:10-13

So basically my problem is, I have a list from 2020 to 2030 and my program said every year is a leap year.

My variables are:

yearList = [2020, 2021, 2022, 2023, 2024, 2025, 2026, 2027, 2028, 2029, 2030]
monthList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
daysOfMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31


    def create_calendar(yearList: list, monthList: list, daysOfMonth: list, numbOfShootingStars: int):
    calendar = {}
    for year in yearList:
        # Create year
        calendar[year] = {}
        for month in monthList:
            # If the list don't have 12 months, it won't loop through all months
            if month == 12 and month   1 == 1: break;
            else:
                # Create monthly data
                calendar[year][month] = {}
                # If February is a leap year, it will have 29 days instead of 28
                if month == 2 and year % 4 == 0:
                        daysOfMonth[month - 1] = 29

                # Create the days and daily data
                for day in range(1, daysOfMonth[monthList.index(month)]   1):
                    calendar[year][month][day] = numbOfShootingStars

    return calendar

Thank you for your help!

  • 1 question, is it possible to use a list like this for this method?

      monthList = [
          {1, 'January'},
          {2, 'February'},
          {3, 'March'},
          {4, 'April'},
          {5, 'May'},
          {6, 'June'},
          {7, 'July'},
          {8, 'August'},
          {9, 'September'},
          {10, 'October'},
          {11, 'November'},
          {12, 'December'}]
    

Then how should I modify my code because I couldn't get it work :(

CodePudding user response:

Okay, I think I solved it, the problem was, I changed to value in the daysOfMonth list at February to 29 and then it stays like that. With this if - else I changed back to it's original state when it is not a leap year.

# If February is a leap year, it will have 29 days instead of 28
                if month == 2 and year % 4 == 0:
                    daysOfMonth[month - 1] = 29
                else:
                    daysOfMonth[month - 1] = 28

CodePudding user response:

If you take a year to be 365.2425 days, this is 365 1/4 - 1/100 1/400. This explains why in the long run you stick to the correct value by adding a whole day every fourth year, but not on every century, but on every fourth century (starting from 0).

A possible implementation is, to tell if the year Y is leap:

Floor(365.2425 Y) - Floor(365.2425 (Y-1)) - 365
  • Related