python练习五

1. 给定一个包含n+1个整数的数组nums,其数字在1到n之间(包含1和n),可知至少存在一个重复的整数,假设只有一个重复的整数,请找出这个重复的数

python 复制代码
def find_difnumber(ls):
    for index in range(0, len(ls)):
        for num in range(index + 1, len(ls)):
            if ls[index] == ls[num]:
                print(f"{ls[index]}这个数字出现了重复")
ls = [1,5,8,6,2,4,1,5,22,13,15,4]
print(ls)
find_difnumber(ls)

2. 找出10000以内能被5或6整除,但不能被两者同时整除的数(函数)

python 复制代码
def find_number():
    for number in range(0, 10000):
        if number % 5 == 0 or number % 6 == 0:
            if number % 5 != number % 6:
                ls.append(number)
    print(ls)
ls = []
find_number()

3. 写一个方法,计算列表所有偶数下标元素的和(注意返回值)

python 复制代码
def count_even():
    count = 0
    for index in range(0, len(ls)):
        if ls[index] % 2 == 0:
            count += index
    print(count)
ls = [1,2,3,4,5,6,7,8,9,10]
count_even()

4. 【选做】某个人进入如下一个棋盘中,要求从左上角开始走,

最后从右下角出来(要求只能前进,不能后退),
问题:共有多少种走法?

0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0

python 复制代码
def count_paths(m, n):
    dp = [[0] * n for _ in range(m)]

    # 初始化第一行和第一列
    for i in range(m):
        dp[i][0] = 1
    for j in range(n):
        dp[0][j] = 1

    # 计算其他位置的路径数
    for i in range(1, m):
        for j in range(1, n):
            dp[i][j] = dp[i-1][j] + dp[i][j-1]

    return dp[m-1][n-1]

# 用户输入行数和列数
m = int(input("请输入棋盘的行数:"))
n = int(input("请输入棋盘的列数:"))

total_paths = count_paths(m, n)
print("从左上角到右下角的所有可能路径数为:", total_paths)

5. 【选做】汉诺塔:

python 复制代码
def hanoi(n, source, target, auxiliary):
    global move_count
    if n == 1:
        move_count += 1
        print(u"将圆盘 1 从 {} 移动到 {}".format(source, target))
        return
    hanoi(n - 1, source, auxiliary, target)
    move_count += 1
    print(u"将圆盘 {} 从 {} 移动到 {}".format(n, source, target))
    hanoi(n - 1, auxiliary, target, source)

# 初始化移动次数为0
move_count = 0

# 测试
num_disks = 4
hanoi(num_disks, 'A', 'C', 'B')
print("总共移动次数:", move_count)

我这里是4层

相关推荐
探物 AI10 分钟前
把 MambaOut 塞进 YOLOv11:会有什么样的反应
python·yolo·计算机视觉
如竟没有火炬39 分钟前
最大矩阵——单调栈
数据结构·python·线性代数·算法·leetcode·矩阵
阳区欠1 小时前
【LangChain】LLM基础介绍
开发语言·python·langchain
Cosolar1 小时前
保姆级 CrewAI 教程:从零构建多智能体协作系统
人工智能·python·架构
GDAL1 小时前
使用 uv 管理 Python 版本
python·uv·版本
真实的菜1 小时前
Redis 从入门到精通(十二):典型业务场景实战 —— 排行榜、限流器、秒杀系统、Session 共享
数据库·redis·python
cup112 小时前
[开源] Meta Assistant / 告别命令行,我为一堆 Python 脚本做了一个 Windows 任务栏的“家”
windows·python·工具·nuitka·脚本运行
小小编程路2 小时前
Python 还有容器类型互转、进制转换、字符编码转换
开发语言·windows·python
Samooyou3 小时前
RAG项目案例--02在线检索&过滤流水线
人工智能·python·ai·全文检索·检索
动能小子ohhh3 小时前
DocForge平台的设计与开发--文件上传接口的实现
开发语言·人工智能·python·langchain·ocr·fastapi