Python 编程实战:从基础语法到算法实现 (1)

在 Python 学习的过程中,通过解决实际的编程问题能够快速提升我们的代码能力和逻辑思维。本文将围绕几个经典的编程练习题展开,涵盖日期处理、素数判断、完数求解、数字操作以及排列组合等多个知识点,带你一起感受 Python 编程的魅力。

一、获取并格式化当前系统时间

在 Python 中,datetime模块为我们提供了丰富的日期和时间处理功能。我们可以轻松获取当前系统时间,并按照指定格式进行格式化输出。

python 复制代码
import datetime
# 获取当前系统时间
now = datetime.datetime.now()
print("当前系统时间:", now)
# 格式化为"年-月-日 小时:分钟:秒"
now_str = now.strftime("%Y-%m-%d %H:%M:%S")
print("格式化后的时间:", now_str)

二、寻找 2~1000 内的回文素数

素数(质数)是指大于 1 且只能被 1 和它本身整除的整数,回文素数则是指既是素数又是回文数的数。要解决这个问题,我们需要分别实现素数判断和回文数判断的功能。

python 复制代码
def is_palindrome(num):
    """判断一个数是否为回文数"""
    num_str = str(num)
    return num_str == num_str[::-1]

def is_prime(num):
    """判断一个数是否为素数"""
    if num <= 1:
        return False
    if num == 2:
        return True
    if num % 2 == 0:
        return False
    for i in range(3, int(num**0.5) + 1, 2):
        if num % i == 0:
            return False
    return True

# 寻找2~1000内的回文素数
palindrome_primes = []
for num in range(2, 1001):
    if is_prime(num) and is_palindrome(num):
        palindrome_primes.append(num)
print("2~1000内的所有回文素数:", palindrome_primes)
python 复制代码
import math

def is_perfect_number(num):
    """判断一个数是否为完数"""
    if num <= 1:
        return False
    sum_factors = 1  # 1是所有大于1的数的真因子
    for i in range(2, int(math.sqrt(num)) + 1):
        if num % i == 0:
            sum_factors += i
            if num // i != i:  # 避免重复添加平方数的情况
                sum_factors += num // i
    return sum_factors == num

print("1000以内的所有完数:")
for num in range(2, 1001):
    if is_perfect_number(num):
        print(num, end=" ")

三、求解 1000 以内的完数

完数是指一个数恰好等于它的所有真因子(除了自身以外的约数)之和。例如 6 的真因子是 1、2、3,而 1+2+3=6,所以 6 是完数。

python 复制代码
import math

def is_perfect_number(num):
    """判断一个数是否为完数"""
    if num <= 1:
        return False
    sum_factors = 1  # 1是所有大于1的数的真因子
    for i in range(2, int(math.sqrt(num)) + 1):
        if num % i == 0:
            sum_factors += i
            if num // i != i:  # 避免重复添加平方数的情况
                sum_factors += num // i
    return sum_factors == num

print("1000以内的所有完数:")
for num in range(2, 1001):
    if is_perfect_number(num):
        print(num, end=" ")
相关推荐
SelectDB17 小时前
Apache Doris Python UDF:让 SQL 直接调用 Python 生态,支撑 Agent 时代复杂业务逻辑
大数据·数据库·python
荣码1 天前
GraphRAG:普通RAG只能回答"点"的问题,我踩了4个坑才搞懂
java·python
金銀銅鐵1 天前
[Python] 基于欧几里得算法,实现分数约分计算器
python·数学
Lyn_Li2 天前
Kaggle Top 5 | 198只股票、200条数据的金融预测——BattleFin高分方案从零复现
python·kaggle·比赛复盘·金融预测
小九九的爸爸2 天前
前端想要入门Agent开发,要具备哪些Python基础?
python·agent·ai编程
阿耶同学2 天前
手把手教你用 LangGraph 搭建三层嵌套 Agent 架构
python·程序员
花酒锄作田2 天前
Pydantic校验配置文件
python
hboot2 天前
AI工程师第四课 - 深度学习入门
pytorch·python·神经网络
ZhengEnCi3 天前
P2M-Matplotlib折线图完全指南-从数据可视化到趋势分析的Python绘图利器
python·matlab·数据可视化
ZhengEnCi3 天前
P2L-Matplotlib饼图完全指南-从数据可视化到图表定制的Python绘图利器
python·matlab