【深基3.例9】月份天数

GitHub跳转原题关系图返回列表

先判断闰年,再用月份天数列表按下标取出答案。

OJ: luogu

题目 ID: P5716

难度:入门

标签:python入门条件判断列表

日期: 2026-07-15 18:07

题意

输入年份 y 和月份 m,输出这一年这个月有多少天。二月需要考虑闰年。

思路

先用闰年规则判断 is_leap。然后准备一个长度为 12 的列表,保存每个月的天数,其中二月根据闰年结果选择 2928

月份是从 1 开始编号,而 Python 列表下标从 0 开始,所以第 m 个月对应 days[m - 1]

brute.py 不适合这题,因为这是规则判断和查表题。

Python 知识

  • 闰年表达式可以复用:(y % 4 == 0 and y % 100 != 0) or (y % 400 == 0)
  • 列表可以保存固定的十二个月天数。
  • 29 if is_leap else 28 是条件表达式,用来决定二月天数。
  • days[m - 1] 体现了“题目编号从 1 开始,列表下标从 0 开始”的转换。

对应的本地 Python 笔记:

  • /home/rainboy/mycode/hugo-blog/content/program_language/python/input_output_and_strings.md:整数输入和列表基础。
  • /home/rainboy/mycode/hugo-blog/content/program_language/python/oj_input_output_cheatsheet.md:单个答案输出。
  • /home/rainboy/mycode/hugo-blog/content/program_language/python/math_tools.md:取模和整数判断。

代码

python
y, m = map(int, input().split())

is_leap = (y % 4 == 0 and y % 100 != 0) or (y % 400 == 0)
days = [31, 29 if is_leap else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

print(days[m - 1], end="")
cpp
/**
 * Author by Rainboy blog: https://rainboylv.com github: https://github.com/rainboylvx
 * rbook: -> https://rbook.roj.ac.cn  https://rbook2.roj.ac.cn
 * rainboy的学习导航网站: https://idx.roj.ac.cn
 * create_at: 2026-07-27 00:00
 * update_at: 2026-07-27 00:00
 */

#include <bits/stdc++.h>
using namespace std;

int main() {
    int y, m; // 年份,月份
    cin >> y >> m;
    // 先判断是否闰年(闰年时 is_leap = 1,平年 = 0)
    int is_leap = (y % 4 == 0 && y % 100 != 0) || (y % 400 == 0);
    // 每个月天数,二月 = 28 + is_leap(闰年时 29)
    int days[] = {31, 28 + is_leap, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    // 月份从 1 开始,数组下标从 0 开始,所以要减 1
    cout << days[m - 1] << endl;
    return 0;
}

Pythonic 写法

match-case:

python
y, m = map(int, input().split())
is_leap = (y % 4 == 0 and y % 100 != 0) or (y % 400 == 0)

match m:
    case 1 | 3 | 5 | 7 | 8 | 10 | 12:
        print(31, end="")
    case 4 | 6 | 9 | 11:
        print(30, end="")
    case 2:
        print(29 if is_leap else 28, end="")

match-case 写法

月份是离散分支,可用 case 1 | 3 | ... 合并同天数月份:

python
y, m = map(int, input().split())
is_leap = (y % 4 == 0 and y % 100 != 0) or (y % 400 == 0)

match m:
    case 1 | 3 | 5 | 7 | 8 | 10 | 12:
        print(31, end="")
    case 4 | 6 | 9 | 11:
        print(30, end="")
    case 2:
        print(29 if is_leap else 28, end="")

复杂度

列表长度固定为 12,时间复杂度 O(1)O(1),空间复杂度 O(1)O(1)

总结

固定月份天数适合用列表查表。只要先处理好二月,再注意 m - 1 的下标转换,代码会比很多层 if 更清楚。