完全日期(日期枚举问题)--- 数学性质题型

题目:

复制代码
"""
    如果一个日期中年月日的各位数字之和是完全平方数,则称为一个完全日期。

    例如: 2021年 6月 5日的各位数字之和为 2 + 0 + 2 + 1 + 6 + 5 = 16 而 16是一个完全平方数,它是 4的平方。所以 2021年 6月 5日是一个完全日期。
    例如: 2021年 6月23日的各位数字之和为 2 + 0 + 2 + 1 + 6 + 2 + 3 = 16 ,是一个完全平方数。所以 2021年 6月 23日也是一个完全日期。

    请问,从 2001年 1月 1 日到 2021 年 12月 31日中,一共有多少个完全日期?

"""

一、暴力枚举

python 复制代码
import math

def digit_sum(year, month, day):
    # print(type(f"{year}{month:02d}{day:02d}"))  # 类型:str
    return sum(map(int, f"{year}{month:02d}{day:02f}"))

def is_perfect_date(sum):
    return int(math.sqrt(sum)) ** 2 == sum

def count_perfect_dates():
    count = 0

    for year in range(2001, 2022):
        for month in range(1, 13): 
              
            max_day = 31 # 大月
            if month in [4,6,9,11]: # 小月
                max_day = 30                 
            elif month == 2:
                if (year % 4 == 0 and year % 100 !=0) or (year % 400 == 0):
                    max_day = 29
                else:
                    max_day = 28
        
            for day in range(1, max_day + 1):
                if is_perfect_date(digit_sum(year, month, day)):
                    count += 1
    return count

print(count_perfect_dates())


"""
格式 02d 的解释:
0: 指定如果数字的位数不足两位时,前面会用零填充。
2: 指定输出数字的最小宽度是 2 位。
d: 代表输出的是一个 整数(decimal integer)

"""

二、Datetime库

python 复制代码
import math 
from datetime import date, timedelta

def is_perfact_date(sum):
    return int(math.sqrt(sum)) ** 2 == sum

def digit_num(cur_date): # 传入日期对象
    return sum(map(int, f"{cur_date.year}{cur_date.month}{cur_date.day}"))

def count_perfect_dates():
    start_date = date(2001, 1, 1)
    end_date = date(2021, 12, 31)

    current_date = start_date
    count = 0

    while current_date <= end_date:
        if is_perfact_date(digit_num(current_date)):
            count += 1
        current_date += timedelta(days=1)
    return count

print(count_perfect_dates())
相关推荐
老赵聊算法、大模型备案4 小时前
北京市生成式人工智能服务已备案信息公告(2025年12月11日)
人工智能·算法·安全·aigc
CoderYanger5 小时前
C.滑动窗口-求子数组个数-越长越合法——2799. 统计完全子数组的数目
java·c语言·开发语言·数据结构·算法·leetcode·职场和发展
厕所博士5 小时前
红黑树原理前置理解—— 2-3 树
算法·2-3树·红黑树原理理解前置
萌>__<新5 小时前
力扣打卡每日一题————除自身外所有元素的乘积
数据结构·算法
xu_yule6 小时前
算法基础—搜索(2)【记忆化搜索+BFS+01BFS+Floodfill]
数据结构·算法
s09071366 小时前
Xilinx FPGA使用 FIR IP 核做匹配滤波时如何减少DSP使用量
算法·fpga开发·xilinx·ip core·fir滤波
老马啸西风6 小时前
成熟企业级技术平台-10-跳板机 / 堡垒机(Bastion Host)详解
人工智能·深度学习·算法·职场和发展
子夜江寒6 小时前
逻辑回归简介
算法·机器学习·逻辑回归
软件算法开发6 小时前
基于ACO蚁群优化算法的多车辆含时间窗VRPTW问题求解matlab仿真
算法·matlab·aco·vrptw·蚁群优化·多车辆·时间窗
another heaven7 小时前
【软考 磁盘磁道访问时间】总容量等相关案例题型
linux·网络·算法·磁盘·磁道