问题:计算有多少个“世界完全对称日”,例如:20200202,20211202
我的思路:
可以在给定范围内对年份做遍历,根据年份生成对应的“完全对称日期字符串”,然后判断该字符串是否可以转换成日期即可。
代码如下:
#!/usr/bin/env python3
"""
在给定年份范围内,计算有多少个“世界完全对称日”,例如:20200202,20211202
"""
import datetime
# 定义最小年份和最大年份
MIN_YEAR = 1000
MAX_YEAR = 9999
def gen_date():
"""
遍历年份,根据年份生成对应的完全对称日期,并判断该日期是否合理。
:return:
"""
total = 0
for i in range(MIN_YEAR, MAX_YEAR + 1):
year = str(i)
# 年份字符串转为列表,并做反转处理
year_list = list(year)
year_list.reverse()
# 列表再次转为日期字符串
rev_year = "".join(year_list)
# 检查月份和日期是否合理
month = int(rev_year[:2])
day = int(rev_year[2:])
# 月份大于12月,或者日期大于31,或者2月日期超过30,直接跳过
if month > 12 or day > 31 or (month == 2 and day > 30):
continue
# 拼接成为“完全对称日期”
date_str = year + rev_year
try:
# 判断日期是否合理:如果合理则打印日期,并累加total数量
dt = datetime.datetime.strptime(date_str, "%Y%m%d").date()
print(dt)
total += 1
except ValueError:
continue
print("-------- Total: %s --------" % total)
if __name__ == '__main__':
gen_date()
执行结果如下:
2001-10-02
2010-01-02
2011-11-02
2020-02-02
2021-12-02
2030-03-02
2040-04-02
2050-05-02
2060-06-02
2070-07-02
2080-08-02
2090-09-02
-------- Total: 12 --------