Number of days in a month in Python

PythonServer Side ProgrammingProgramming

Suppose we have one year Y and a month M, we have to return the number of days of that month for the given year. So if the Y = 1992 and M = 7, then the result will be 31, if the year is 2020, and M = 2, then the result is 29.

To solve this, we will follow these steps −

• if m = 2, then
• if y is a leap year, return 29, otherwise 28
• make an array with elements [1,3,5,7,8,10,12]
• if m is in the list, then return 31, otherwise, return 30.

Example(Python)

Let us see the following implementation to get a better understanding −

Live Demo

class Solution(object):
def numberOfDays(self, y, m):
leap = 0
if y% 400 == 0:
leap = 1
elif y % 100 == 0:
leap = 0
elif y% 4 == 0:
leap = 1
if m==2:
return 28 + leap
list = [1,3,5,7,8,10,12]
if m in list:
return 31
return 30
ob1 = Solution()
print(ob1.numberOfDays(2020, 2))

Input

2020
2

Output

29
Published on 27-Feb-2020 07:05:39