题目
编写函数接收 YYYY-MM-DD 格式的生日字符串,返回周岁年龄,需考虑今年生日是否已过。输入契约:日期字符串;输出契约:完整年数整数。公开样例在 2025-01-20 计算 "2000-01-15" 得 25。隐藏测试:2025-01-01 对 "2000-12-31" 得 24;2025-06-14 对 "2000-06-15" 得 24。
解题思路
先用 strptime 解析生日并转成 date,再取今天日期;年龄初值为年份差,若今天的 (月, 日) 元组小于生日的 (月, 日),说明今年生日未到,年龄减 1。元组比较天然按月和日逐项比较,避免手写分支。
参考实现要点
datetime.strptime(birth_date_str, "%Y-%m-%d").date() 得到生日;date.today() 得到今天;age = today.year - birth.year;用 if (today.month, today.day) < (birth.month, birth.day): age -= 1;返回整数。
常见错误
原文指出只减年份而不检查今年生日是否已过会算错。另一个边界坑是生日当天:元组相等时不减 1,应当算作已满周岁;隐藏用例中 6 月 14 日对 6 月 15 日生日返回 24,正好覆盖“差一天”的情况。
验证方式
在测试中固定“今天”的日期,逐一验证公开样例和两个隐藏用例;再测生日当天,确认年份差不再减 1,结果符合周岁定义。
代码示例
from datetime import datetime, date
def calculate_age(birth_date_str):
birth = datetime.strptime(birth_date_str, "%Y-%m-%d").date()
today = date.today()
age = today.year - birth.year
if (today.month, today.day) < (birth.month, birth.day):
age -= 1
return age