Counting number of days in a given month of a year
Learn how to solve the 'Counting number of days in a given month of a year' problem. This detailed resource details brute force and optimized approaches.
Problem Statement
Write a function days_in_month(month, year) that takes an integer month (1-12) and an integer year, and returns the number of days in that month.
Remember:
- Months with 31 days: January(1), March(3), May(5), July(7), August(8), October(10), December(12)
- Months with 30 days: April(4), June(6), September(9), November(11)
- February(2): 28 days normally, 29 days in a leap year
- Leap year: divisible by 4, but not by 100, unless also divisible by 400
- •1 <= month <= 12
- •1 <= year <= 9999
Examples
days_in_month(2, 2024)
29
2024 is divisible by 4 and not by 100, so it's a leap year. February has 29 days.
days_in_month(1, 2023)
31
January always has 31 days regardless of the year.
days_in_month(2, 1900)
28
1900 is divisible by 100 but not by 400, so it's NOT a leap year. February has 28 days.
Need a Hint?
Edge Cases to Watch
- Empty list or null input variables
- Single item lists/arrays
- Extremely large input bounds causing integer or stack overflow
Ready to Solve?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.